2016-05-04 85 views
0

我试图给CSV文件的第二列中的每一行添加一个字符串(@ example.com),并用新字符串替换旧字符串,以便CSV文件是用新字符串保存。例如:替换CSV文件中的字符串并写入文件

老:

John Smith, JohnSmith, Staff 

新:

John Smith, [email protected], 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 

正如你所看到的,我只是用文件f2玩弄试图用新数据覆盖CSV。但是当我尝试用'w'或'a'打开文件时,我一直得到一个IOError:文件未写入对于f2.write(row)。但是,当我只打印行变量时,它会正确地打印出我需要的内容。我很可能得到这个错误,因为我正在阅读并试图在同一时间写它。

如何将@ example.com添加到第二列中的每一行并保存,以便它实际上在同一个CSV文件中被更改?

我知道它非常杂乱的代码,但我只是一个初学者。这是我处理它的方式,请让我休息一下。帮助将不胜感激。

回答

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) 
相关问题