Python修改CSV的内容并重新保存

时间:2017-07-06 10:40:48

标签: python csv

要求程序搜索一行,然后在重新保存之前调整CSV的特定元素。

任何帮助表示赞赏!

import csv
import os
username=input('Enter username: ')
with open ('user.csv', 'r') as user:
    reader=csv.reader(user, delimiter=',')
    print(reader)

with open ('newuser.csv', 'w') as newdetail:
    writer=csv.writer(newdetail, delimiter=',')
    for colomn in reader:
        if username in coloum[1]:
            print('User found! \n')
            print('UserID: '+colomn[0])
            print('Username: '+colomn[1])
            print('Interest: '+colomn[2])
            change = (column[2])
            change = input("What is your new interest?")
            print(colomn[2]+' has been changed to ', change)
        writer.writerow(colomn)
os.remove('user.csv')
os.rename('newuser.csv', 'user.csv')

目前的错误是:

dir/ line 10, in <module>
    for colomn in reader:
ValueError: I/O operation on closed file.

非常感谢,这是我现在所处的位置。目前只打印正在编辑的单行,而不是所有其他尚未调整的电影。

import csv
import os
new = []
username=input('Enter movie: ')
with open ('movies.csv', 'r') as user:
    reader=csv.reader(user, delimiter=',')
    #print(reader)

    with open ('newmovies.csv', 'w') as newdetail:
        writer=csv.writer(newdetail, delimiter=',')
        for colomn in reader:
            if username in colomn[1]:
                print('Movie found!')
                print('MovieID: '+colomn[0])
                print('Movie name: '+colomn[1])
                print('Interest: '+colomn[2])
        choice = input("what is your new interest?")
        print('Interest has been changed to ', choice)
        new = [(colomn[0]),(colomn[1]),(choice)]
        writer.writerow(new)
os.remove('movies.csv')
os.rename('newmovies.csv', 'movies.csv')

1 个答案:

答案 0 :(得分:0)

reader对象不包含数据,但只能直接访问该文件。关闭user.csv文件后(退出with范围时)reader不再有用。

尝试将第二个with放在第一个范围内:

with open ('user.csv', 'r') as user:
    reader=csv.reader(user, delimiter=',')
    print(reader)
    with open ('newuser.csv', 'w') as newdetail:
        writer=csv.writer(newdetail, delimiter=',')
        for colomn in reader:
            if username in colomn[1]:
                print('User found! \n')
                print('UserID: '+colomn[0])
                print('Username: '+colomn[1])
                print('Interest: '+colomn[2])
                change = (column[2])
                change = input("What is your new interest?")
                print(colomn[2]+' has been changed to ', change)
            writer.writerow(colomn)

P.S。 - 修正第11行 - colomn而不是coloum