你如何在 Python 中将文件读入列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3925614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you read a file into a list in Python?
提问by user474713
I want to prompt a user for a number of random numbers to be generated and saved to a file. He gave us that part. The part we have to do is to open that file, convert the numbers into a list, then find the mean, standard deviation, etc. without using the easy built-in Python tools.
我想提示用户生成一些随机数并将其保存到文件中。他给了我们那部分。我们要做的部分是打开该文件,将数字转换为列表,然后在不使用简单的内置 Python 工具的情况下找到均值、标准差等。
I've tried using openbut it gives me invalid syntax (the file name I chose was "numbers" and it saved into "My Documents"automatically, so I tried open(numbers, 'r')and open(C:\name\MyDocuments\numbers, 'r')and neither one worked).
我已经尝试使用open,但它给了我无效的语法(我选择的文件名是“数字”,它保存到"My Documents"自动,所以我尝试open(numbers, 'r')和open(C:\name\MyDocuments\numbers, 'r')并没有一个工作)。
回答by phimuemue
f = open("file.txt")
lines = f.readlines()
Look over here. readlines()returns a list containing one line per element. Note that these lines contain the \n(newline-character) at the end of the line. You can strip off this newline-character by using the strip()-method. I.e. call lines[index].strip()in order to get the string without the newline character.
看这边。readlines()返回一个列表,每个元素包含一行。请注意,这些行在行尾包含\n(换行符)。您可以使用strip()- 方法去除这个换行符。即调用lines[index].strip()以获取没有换行符的字符串。
As joaquin noted, do not forget to f.close()the file.
正如 joaquin 所指出的,不要忘记f.close()文件。
Converting strint to integers is easy: int("12").
转换strint为整数很简单:int("12")。
回答by Mark Ransom
You need to pass a filename string to open. There's an extra complication when the string has \in it, because that's a special string escape character to Python. You can fix this by doubling up each as \\or by putting a rin front of the string as follows: r'C:\name\MyDocuments\numbers'.
您需要将文件名字符串传递给open. 当字符串中有一个额外的复杂性时\,因为它是 Python 的特殊字符串转义字符。您可以通过为每个翻倍解决这个问题\\或者通过把一个r在前面的字符串如下:r'C:\name\MyDocuments\numbers'。
Edit:The edits to the question make it completely different from the original, and since none of them was from the original poster I'm not sure they're warrented. However it does point out one obvious thing that might have been overlooked, and that's how to add "My Documents" to a filename.
编辑:对问题的编辑使它与原来的完全不同,而且由于它们都不是来自原始海报,我不确定它们是否受到警告。然而,它确实指出了一件可能被忽视的明显事情,那就是如何将“我的文档”添加到文件名中。
In an English version of Windows XP, My Documentsis actually C:\Documents and Settings\name\My Documents. This means the opencall should look like:
在英文版的 Windows XP 中,My Documents实际上是C:\Documents and Settings\name\My Documents. 这意味着open调用应如下所示:
open(r"C:\Documents and Settings\name\My Documents\numbers", 'r')
I presume you're using XP because you call it My Documents- it changed in Vista and Windows 7. I don't know if there's an easy way to look this up automatically in Python.
我假设您使用的是 XP,因为您称之为 XP My Documents- 它在 Vista 和 Windows 7 中发生了变化。我不知道是否有一种简单的方法可以在 Python 中自动查找。
回答by joaquin
hdl = open("C:/name/MyDocuments/numbers", 'r')
milist = hdl.readlines()
hdl.close()
回答by Corey Goldberg
with open('C:/path/numbers.txt') as f:
lines = f.read().splitlines()
this will give you a list of values (strings) you had in your file, with newlines stripped.
这将为您提供文件中的值(字符串)列表,并删除换行符。
also, watch your backslashes in windows path names, as those are also escape chars in strings. You can use forward slashes or double backslashes instead.
另外,请注意 Windows 路径名中的反斜杠,因为它们也是字符串中的转义字符。您可以改用正斜杠或双反斜杠。
回答by Srikar Appalaraju
Two ways to read file into list in python (note these are not either or) -
在python中将文件读入列表的两种方法(注意这些不是或) -
- use of
with- supported from python 2.5 and above - use of list comprehensions
- 使用
with- 从 python 2.5 及更高版本支持 - 列表推导式的使用
1. use of with
1. 使用 with
This is the pythonic way of opening and reading files.
这是打开和读取文件的pythonic方式。
#Sample 1 - elucidating each step but not memory efficient
lines = []
with open("C:\name\MyDocuments\numbers") as file:
for line in file:
line = line.strip() #or some other preprocessing
lines.append(line) #storing everything in memory!
#Sample 2 - a more pythonic and idiomatic way but still not memory efficient
with open("C:\name\MyDocuments\numbers") as file:
lines = [line.strip() for line in file]
#Sample 3 - a more pythonic way with efficient memory usage. Proper usage of with and file iterators.
with open("C:\name\MyDocuments\numbers") as file:
for line in file:
line = line.strip() #preprocess line
doSomethingWithThisLine(line) #take action on line instead of storing in a list. more memory efficient at the cost of execution speed.
the .strip()is used for each line of the file to remove \nnewline character that each line might have. When the withends, the file will be closed automatically for you. This is true even if an exception is raised inside of it.
将.strip()用于文件的每一行删除\n换行符,每一行都可能。当with结束时,文件将自动为您关闭。即使在其中引发异常也是如此。
2. use of list comprehension
2. 列表理解的使用
This could be considered inefficient as the file descriptor might not be closed immediately. Could be a potential issue when this is called inside a function opening thousands of files.
这可能被认为是低效的,因为文件描述符可能不会立即关闭。当在打开数千个文件的函数中调用它时,这可能是一个潜在的问题。
data = [line.strip() for line in open("C:/name/MyDocuments/numbers", 'r')]
Note that file closing is implementation dependent. Normally unused variables are garbage collected by python interpreter. In cPython (the regular interpreter version from python.org), it will happen immediately, since its garbage collector works by reference counting. In another interpreter, like Jython or Iron Python, there may be a delay.
请注意,文件关闭取决于实现。通常未使用的变量是由 python 解释器收集的垃圾。在 cPython(来自 python.org 的常规解释器版本)中,它会立即发生,因为它的垃圾收集器通过引用计数工作。在另一个解释器中,如 Jython 或 Iron Python,可能会有延迟。
回答by ohe
The pythonic way to read a file and put every lines in a list:
读取文件并将每一行放入列表的pythonic方法:
from __future__ import with_statement #for python 2.5
with open('C:/path/numbers.txt', 'r') as f:
lines = f.readlines()
Then, assuming that each lines contains a number,
然后,假设每行包含一个数字,
numbers =[int(e.strip()) for e in lines]
回答by Tom
To summarize a bit from what people have been saying:
总结一下人们所说的话:
f=open('data.txt', 'w') # will make a new file or erase a file of that name if it is present
f=open('data.txt', 'r') # will open a file as read-only
f=open('data.txt', 'a') # will open a file for appending (appended data goes to the end of the file)
If you wish have something in place similar to a try/catch
如果你希望有一些类似于 try/catch 的东西
with open('data.txt') as f:
for line in f:
print line
I think @movieyoda code is probably what you should use however
我认为@movieyoda 代码可能是您应该使用的代码
回答by Stefan Gruenwald
If you have multiple numbers per line and you have multiple lines, you can read them in like this:
如果每行有多个数字并且有多行,则可以像这样读取它们:
#!/usr/bin/env python
from os.path import dirname
with open(dirname(__file__) + '/data/path/filename.txt') as input_data:
input_list= [map(int,num.split()) for num in input_data.readlines()]

