[英]List of lines from file in Python?
Is there a way to read the lines of a file and convert it to a Python list? 有没有办法读取文件的行并将其转换为Python列表? For example:
例如:
someFile: someFile:
Hello
World
Script: 脚本:
>>>x = someFile.listLines()
>>>print x
['Hello', 'World']
You want the readlines
method of a file
object. 您需要
file
对象的readlines
方法。
fileobject = open(datafilename)
lines = fileobject.readlines()
Note that you (usually) don't need this. 请注意,您(通常)不需要此。 You can iterate over the file object directly and save yourself from having to store the whole file in memory:
您可以直接遍历文件对象,而不必将整个文件存储在内存中:
for line in fileobject:
#do something with the line
don't forget to close your fileobject when you're done! 完成后,别忘了关闭文件对象! (context managers are quite helpful for that)
(上下文管理器对此非常有帮助)
Also, note that the lines will end with a newline ( "\\n"
), but you can easily filter that off using .rstrip("\\n")
on the strings in the list or some variant in the str.strip
family. 另外,请注意,这些行将以换行符(
"\\n"
)结尾,但是您可以使用.rstrip("\\n")
对列表中的字符串或str.strip
系列的某些变体轻松过滤掉这些str.strip
。 eg: 例如:
stripped_lines = [ line.rstrip("\n") for line in fileobject ]
In other words, 换一种说法,
lines = fileobject.readlines()
gives you the same thing as 给你一样的东西
lines = list(fileobject)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.