我有一个跟随代码很好用,而两个列表都在代码中定义:
dataOld = ['apples', 'pineapple']
dataNew = ['apples', 'pineapple', 'avocado']
for data in dataNew:
if data not in dataOld:
dataUpdated = dataOld.append(data)
现在我想将dataOld
的源代码更改为外部文件。下面描述的更新不起作用。我可能在某处犯了一些初学者的错误,但我不知道在哪里?
import os
if os.path.exists('testfile.txt'):
dataFile = open('testfile.txt', 'r')
dataOld = dataFile.readlines()
for line in dataOld:
lineUpdated = line.rstrip("\n")
else:
dataFile = open('testfile.txt', 'w')
dataOld = set()
dataNew = ['apples', 'pineapple', 'avocado']
for data in dataNew:
if data not in dataOld:
dataUpdated = dataOld.append(data)
dataFile.write(str(data+"\n"))
dataFile.close()
答案 0 :(得分:0)
您正在尝试更改for循环中的列表:
for line in dataOld:
lineUpdated = line.rstrip("\n")
这会为lineUpdated
分配一些内容,但不会更改dataOld
中的值。
尝试列表理解和作业:
dataOld = [line.rstrip("\n") for line in dataOld]
还尝试使用set
:
dataNew = set(['apples', 'pineapple', 'avocado'])
dataOld = set(line.rstrip("\n") for line in dataOld)
dataUpdated = dataNew - dataOld
您的文件处理也需要重新处理,您无法写入打开的文件进行读取。尝试使用with
语句:
if os.path.exists('testfile.txt'):
with open('testfile.txt', 'r') as dataFile:
dataOld = dataFile.readlines()
else:
dataOld=set()
...
with open('testfile.txt', 'a') as dataFile:
for data in dataUpdated:
dataFile.write(str(data)+"\n")