简体   繁体   English

Python 2.7-在文本文件的列表中添加和删除项目

[英]Python 2.7 - add and remove items from a list in a text file

For example I have a text file with a list. 例如,我有一个带有列表的文本文件。

What I want to do. 我想做的事。

Read the text file and find the list. 阅读文本文件并找到列表。 Add/remove an item from the list. 从列表中添加/删除项目。 Write the amended list back to the text file or at least a new version of the text file. 将修改后的列表写回到文本文件或至少新版本的文本文件中。

I can do this in memory as shown below. 我可以在内存中执行此操作,如下所示。 But want to open a file, edit the list and then write to disk. 但是要打开文件,编辑列表,然后写入磁盘。 I'm new to Python, so some code examples would be great. 我是Python的新手,所以一些代码示例会很棒。

myfile = “/users/admin/desktop/list.txt”
mylist = ["red", "blue", "green", "yellow", "white"]
myitem = "orange"

with open(myfile) as f:
    mylist = list(f)
    mylist.append(myitem)  


with open(myfile) as f:
    mylist = list(f)
    mylist.remove(myitem)

Nothing fancy, just a simple replace all of the text in the file with contents of the new file, use eval() to convert text to a list. 没什么,只是简单地用新文件的内容替换文件中的所有文本,使用eval()将文本转换为列表。 You should probably create a function that writes list to the file and call it after you change the list: 您可能应该创建一个将列表写入文件并在更改列表后调用它的函数:

print(mylist)
print(open(myfile).read())

with open(myfile) as f:
    mylist = eval(f.read())
    mylist.append(myitem)

with open(myfile, 'w') as f:
    f.write(str(mylist))

print(mylist)
print(open(myfile).read())

with open(myfile) as f:
    mylist = eval(f.read())
    mylist.remove(myitem)

with open(myfile, 'w') as f:
    f.write(str(mylist))

print(mylist)
print(open(myfile).read())


Output: 输出:

['red', 'blue', 'green', 'yellow', 'white']
["red", "blue", "green", "yellow", "white"]
['red', 'blue', 'green', 'yellow', 'white', 'orange']
['red', 'blue', 'green', 'yellow', 'white', 'orange']
['red', 'blue', 'green', 'yellow', 'white']
['red', 'blue', 'green', 'yellow', 'white']

If the point of the file is simply to have persistent storage of the list, have you considered just using pickle? 如果文件的目的仅仅是持久存储列表,那么您是否考虑过仅使用pickle? https://docs.python.org/2/library/pickle.html https://docs.python.org/2/library/pickle.html

If it truly is comma seperated, I'd use the csv module ( docs ). 如果确实是逗号分隔,则可以使用csv模块( docs )。 It's fairly straightforward. 这很简单。

import csv

with open(myfile) as rfp, open(myfile + '.v2', 'w') as wfp:
    reader = csv.reader(rfp)
    writer = csv.writer(wfp)
    for row in reader:
        row.append(myitem)
        # do something here I suppose
        row.remove(myitem)
        writer.writerow(row)

You may have to use the docs to adjust the reader and writer settings to your operating system and/or file format but I've had great success with that module. 您可能需要使用文档来将读取器和写入器设置调整为您的操作系统和/或文件格式,但是我对该模块取得了巨大的成功。

Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM