简体   繁体   English

导入、读取和添加到保存在文本文件中的列表的最佳方法是什么?

[英]What is the Best Method for Importing, Reading and Adding to a List Saved in a Text File?

我如何在 Python 中调用外部 .txt 文件中的列表并能够在我的代码中使用它并添加到其中?

There are many ways to do this.有很多方法可以做到这一点。 Here is one very simple way (for pure demo purposes):这是一种非常简单的方法(用于纯演示目的):

(within the same directory, create two files) (在同一个目录下,创建两个文件)

File 1: mydata.py - this store the "external list"文件 1: mydata.py - 这个存储“外部列表”

dummy = [1, 2, 3]

File 2: main_program.py - this import the "external list" and print it文件 2: main_program.py - 导入“外部列表”并打印它

from mydata import dummy
print(dummy)
# print out [1, 2, 3]

Then just run the python code like this:然后像这样运行python代码:

python main_program.py

Reference: Importing variables from another file参考: 从另一个文件导入变量

It isn't clear what you mean when you say external list, so I'm going to assume that you mean data stored in a text file.当您说外部列表时,您的意思不清楚,所以我假设您的意思是存储在文本文件中的数据。 To read from a file, use Python's file methods.要读取文件,请使用 Python 的文件方法。 If you want to read the entire contents of the file, use the read method of the file object.如果要读取文件的全部内容,请使用文件对象的读取方法。

f = open("mylist.txt", "r")
contents = f.read()
f.close()

With a list, however, it may be useful to read the file one line at a time.但是,对于列表,一次读取一行文件可能会很有用。 In this case, you can either use the readline method在这种情况下,您可以使用 readline 方法

f = open("mylist.txt", "r")
line1 = f.readline()
line2 = f.readline()
f.close()

or loop over the file object或循环遍历文件对象

f = open("mylist.txt", "r")
for line in f:
    #do something with line
f.close()

To modify the file, open the file in write or append mode and write to it.要修改文件,请以写入或追加模式打开文件并写入。

f = open("mylist.txt", "w") #Overwrites any data in the file
f.write("foo\n")
f.write("bar\n")
f.close()

f = open("mylist.txt", "a") #Preserves and adds to data in the file
f.write("foo\n")
f.write("bar\n")
f.close()

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

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