python - 如何从python中的文件中获取列表

标签 python python-3.x file

我正在尝试获取列表中文件的内容。供引用:这些是文件的内容:

1. item1
2. item2
3. item3

我能够打开文件,当我执行 file.read() 时,我从解释器得到的只是一个空字符串:

>>> file = open("C:\\Users\\vivrd\\Desktop\\testing.txt")
>>> file.read()
''

如果我执行 file.readlines(),它会显示一个列表,但即使 python 文档说 file.readlines() 返回一个列表,每当我尝试为其分配一个变量(以访问列​​表),我得到的只是一个空列表:

>>> file.readlines() 
['1. item1\n', '2. item2\n', '3. item3'] #returns the list   
>>> item = file.readlines()
>>> item #but the list is empty!
[]

我也试过遍历文件,但它没有打印出任何东西:

>>> for line in file:
print(line)


>>> 

此外,由于某些原因,file.readlines() 只工作一次。我第二次尝试,解释器甚至没有显示任何内容:

>>> file.readlines()
[]

我的目标是得到一个如下所示的列表:["1.item1", "2.item2", "3.item3"] 甚至带有转义序列(虽然不是更可取): ["1.item1\n", "2.item2\n", "3.item3"]

我怎样才能走到这一步?谢谢!

最佳答案

它只会工作一次,因为在那之后,python 完成读取文件 (here's a question that discusses this in detail)。读取一次并将其存储在变量中:

>>> f = open("C:\\Users\\vivrd\\Desktop\\testing.txt")
>>> items = f.readlines() # items should now be a list of lines in the file
>>> f.close() # make sure to close the file

如果您想重新阅读,请使用 seek 将“光标”移回文件开头(在关闭之前):

>>> items = f.readlines()
>>> f.seek(0)
>>> more_items = f.readlines()
>>> f.close()

关于python - 如何从python中的文件中获取列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52619148/

相关文章:

PYTHON 文件更新在 VSCODE 中导入时未反射(reflect)出来

python - 为什么 Python 的 .decode ('cp037' ) 不适用于特定的二进制数组?

python - 使用 Telnet.write() 时出现类型错误

python - 为什么 contextmanager 不重新引发异常?

java - logback有时不写入日志文件,有时不回滚日志文件

python - 在 zip 文件中递归列出所有目录,无需在 python 中解压

ruby - 寻找 "0"或使用倒带方法?

python - Python ndimage generic_filter 的条件逻辑

python - Python 是否有返回模块中所有属性的方法?

python-3.x - seaborn 如何设置样式和字体大小