繁体   English   中英

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

[英]Open CSV, replace text AND add new string line by line AND save to original file

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

您只需要打开文件一次即可读取,然后一次写入即可,并且不需要使用两个单独的文件。 文件读取和写入的次数越少,脚本运行的速度就越快。

一些附带要点:

  • 始终with open(...) as f使用with open(...) as f
  • 一种更易读的字符替换方法是使用str.replace()
  • 您可能想看看str.splitlines()

而且,从此示例看起来,您看起来根本没有在代码中使用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)

你太复杂了。

首先,阅读线,施加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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM