你如何在Python中将文件读入列表?

use*_*713 129 python file

我想提示用户生成一些随机数并保存到文件中.他给了我们这一部分.我们要做的部分是打开该文件,将数字转换为列表,然后找到平均值,标准偏差等,而不使用简单的内置Python工具.

我已经尝试使用open,但它给了我无效的语法(我选择的文件名是"数字",它保存到"My Documents"自动,所以我尝试open(numbers, 'r')open(C:\name\MyDocuments\numbers, 'r')并没有一个工作).

Cor*_*erg 227

with open('C:/path/numbers.txt') as f:
    lines = f.read().splitlines()
Run Code Online (Sandbox Code Playgroud)

这将为您提供文件中的值(字符串)列表,并删除换行符.

另外,在Windows路径名中查看反斜杠,因为它们也是字符串中的转义字符.您可以使用正斜杠或双反斜杠.

  • AttributeError:'list'对象没有属性'splitlines' (8认同)

Sri*_*aju 100

在python中将文件读入列表的两种方法(注意这些不是或者) -

  1. 使用with- 从python 2.5及更高版本支持
  2. 使用列表推导

使用 with

这是打开和读取文件的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.
Run Code Online (Sandbox Code Playgroud)

.strip()用于文件的每一行删除\n换行符,每一行都可能.当with结束时,文件将自动为您关闭.即使在其中引发异常,也是如此.

2.使用列表理解

这可能被认为是低效的,因为文件描述符可能不会立即关闭.当在一个打开数千个文件的函数内调用它时可能是一个潜在的问题.

data = [line.strip() for line in open("C:/name/MyDocuments/numbers", 'r')]
Run Code Online (Sandbox Code Playgroud)

请注意,文件关闭取决于实现.通常未使用的变量是由python解释器收集的垃圾.在cPython(python.org的常规解释器版本)中,它会立即发生,因为它的垃圾收集器通过引用计数工作.在另一个解释器中,如Jython或Iron Python,可能会有延迟.

  • 这不会关闭打开的文件. (11认同)

phi*_*mue 54

f = open("file.txt")
lines = f.readlines()
Run Code Online (Sandbox Code Playgroud)

看看这里.readlines()返回一个包含每个元素一行的列表.请注意,这些行包含\n行尾的(换行符).您可以使用strip()-method 剥离此换行符.即调用lines[index].strip()以获取没有换行符的字符串.

正如joaquin所说,不要忘记f.close()文件.

将strint转换为整数很简单:int("12").


ohe*_*ohe 14

读取文件并将每行放入列表的pythonic方法:

from __future__ import with_statement #for python 2.5
with open('C:/path/numbers.txt', 'r') as f:
    lines = f.readlines()
Run Code Online (Sandbox Code Playgroud)

然后,假设每行包含一个数字,

numbers =[int(e.strip()) for e in lines]
Run Code Online (Sandbox Code Playgroud)


Mar*_*som 8

您需要将文件名字符串传递给open.当字符串包含在内时会有一个额外的复杂性\,因为这是Python的特殊字符串转义字符.您可以通过将每个加倍\\或通过将r字符串放在字符串前面来解决此问题,如下所示:r'C:\name\MyDocuments\numbers'.

编辑:对问题的编辑使它与原始版本完全不同,因为它们都不是来自原始海报,所以我不确定它们是否已经过警告.然而,它确实指出了一个可能被忽视的显而易见的事情,那就是如何将"我的文档"添加到文件名中.

My Documents实际上,在英文版的Windows XP中C:\Documents and Settings\name\My Documents.这意味着open调用应该如下所示:

open(r"C:\Documents and Settings\name\My Documents\numbers", 'r')
Run Code Online (Sandbox Code Playgroud)

我认为你正在使用XP,因为你称它为My Documents- 它在Vista和Windows 7中发生了变化.我不知道是否有一种简单的方法可以在Python中自动查找.


joa*_*uin 5

hdl = open("C:/name/MyDocuments/numbers", 'r')
milist = hdl.readlines()
hdl.close()
Run Code Online (Sandbox Code Playgroud)


Tom*_*Tom 5

总结一下人们所说的话:

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)
Run Code Online (Sandbox Code Playgroud)

如果你希望有一些类似于 try/catch 的东西

with open('data.txt') as f:
    for line in f:
        print line
Run Code Online (Sandbox Code Playgroud)

我认为@movieyoda 代码可能是您应该使用的代码