简体   繁体   中英

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? For example:

someFile:

Hello
World

Script:

>>>x = someFile.listLines()
>>>print x
['Hello', 'World']

You want the readlines method of a file object.

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. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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