要求程序搜索一行,然后在重新保存之前调整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')
答案 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