【问题标题】:Open CSV, replace text AND add new string line by line AND save to original file打开 CSV,替换文本并逐行添加新字符串并保存到原始文件
【发布时间】:2017-12-22 21:46:25
【问题描述】:

考虑以下 CSV:

"""tom"""
""fred""
"henry"
Jack
"""mary"""

下面会查找我定义的一些字符,删除它们,然后在每行(行)的末尾添加一个字符串。它“有效”,但我不确定我是否以正确的方式进行......在我看来,应该打开、编辑和保存原始文件。我将针对数千个 CSV 文件运行它,因此它会变得非常混乱。

import csv
s = open('Book1.csv','r').read()
chars = ('$','%','^','*','"','_') # etc
for c in chars:
  s = ''.join( s.split(c) )
out_file = open('Book2.csv','w')
out_file.write(s)
out_file.close()
output = ""
file_name = 'Book2.csv'
string_to_add = "@bigfoot.com"
with open(file_name, 'r') as f:
    file_lines = [''.join([x.strip(), string_to_add, '\n']) for x in f.readlines()]
with open(file_name, 'w') as f:
    f.writelines(file_lines)


tom@bigfoot.com
fred@bigfoot.com
henry@bigfoot.com
Jack@bigfoot.com
mary@bigfoot.com

【问题讨论】:

  • 它不是真正的 csv / 至少根本不使用 csv 模块,而是使用文本处理。字符可以在字符串的中间吗?
  • 为什么不读取文件行,执行替换+添加然后写回原始文件?
  • no 字符将始终位于原始字符串的任一端,删除字符后要添加的字符串将始终附加到末尾

标签: python python-3.x python-2.7 csv


【解决方案1】:

您只需要打开文件一次读取,一次写入,您不需要使用两个单独的文件。您执行的文件读写越少,您的脚本运行速度就越快。

附带几点:

此外,从这个示例来看,您实际上并没有在代码中使用 csv 模块。

以下是我的建议:

chars = ('$', '%', '^', '*', '"', '_')
string_to_add = '@bigfoot.com'

with open('tmp', 'r') as f:
    s = f.read()

# Replace unwanted characters
for c in chars:
    s = s.replace(c, '')

# Append line ending
s = '\n'.join(line + string_to_add for line in s.splitlines())

with open('tmp', 'w') as f:
    f.write(s)

【讨论】:

    【解决方案2】:

    你太复杂了。

    首先,阅读这些行,在行上应用strip 以删除字符串开头或结尾的所有字符(包括换行符,否则它将不起作用)。在这里使用带有replace 的循环是非常低效且不必要的,因为strip 一次性完成了您想要的操作。

    然后,将这些行写回同一个文件,附加域和换行符

    input_file = 'Book1.csv'
    chars = '$%^*"_\n'  # etc notice the \n (linefeed)
    with open(input_file) as f:
        lines = [x.strip(chars) for x in f]
    with open(input_file,"w") as f:
        f.writelines("{}@bigfoot.com\n".format(x) for x in lines)
    

    【讨论】:

      猜你喜欢
      • 2019-01-29
      • 2019-04-05
      • 2021-02-04
      • 2018-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多