打开CSV,替换文本,逐行添加新字符串并保存到原始fi

2024-05-29 11:46:32 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑以下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

Tags: 文件csvnamecomopenfredoutfile
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)

您只需要打开一次文件就可以读取,一次可以写入,而且不需要使用两个单独的文件。文件读写越少,脚本运行越快。你知道吗

一些附带的要点:

  • 始终如一地使用with open(...) as f
  • 一种更可读的替换字符的方法是使用^{}。你知道吗
  • 您可能想签出^{}

而且,从这个例子看,您根本不像是在代码中使用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)

相关问题 更多 >

    热门问题