我正在尝试将字符串(@ example.com)添加到CSV文件中第2列的每一行,并用新字符串替换旧字符串,以便使用新字符串保存CSV文件。例如:
旧:
John Smith, JohnSmith, Staff
新:
John Smith, JohnSmith@example.com, Staff
这是我的实际代码:
f2 = open('/root/Downloads/UserAccounts/Users-7-21-2014.csv','w')
f3 = open('/root/Downloads/UserAccounts/Users-12-06-2012.csv')
f4 = open('/root/Downloads/UserAccounts/Users-05-13-2007.csv')
# adds the first and last name together and adds @examples to userID
# but does not replace first and last name into one
for row in f2.readlines():
m = row.split(',')[0], row.split(',')[1]
j = row.split(',')[2] + "@example.com"
row = row.replace(row.split(',')[2], j)
f2.write(row) #error is here
# adds first and last name together
# but does not replace first and last name into one
for row in f3.readlines():
n = row.split(',')[0], row.split(',')[1]
# print n
# adds @example.com to username
for row in f4.readlines():
t = row.split(',')[1] + "@example.com"
row = row.replace(row.split(',')[1], t)
# print row
正如您所看到的,我只是在尝试使用新数据覆盖CSV时使用f2文件。但是当我尝试使用'w'或'a'打开文件时,我不断收到 IOError:文件未打开 f2.write(row) 。但是当我打印行变量时,它会打印出我需要的内容。我可能会收到此错误,因为我正在阅读并试图同时写它。
如何将@ example.com添加到第二列中的每一行并保存,以便在同一个CSV文件中实际更改?
我知道它的代码非常混乱,但我只是一个初学者。这是我处理它的方式,所以给我一个休息时间。帮助将不胜感激。
答案 0 :(得分:0)
不建议在同一文件中读写。无论如何你都希望这样做我建议你这样做:
with open('/root/Downloads/UserAccounts/Users-7-21-2014.csv','r') as f2:
Rows = f2.readlines()
with open('/root/Downloads/UserAccounts/Users-7-21-2014.csv','w') as f2:
for row in Rows:
#do something with the row here
f2.write(row)