Sil*_*ost 2057
with open(filename) as f:
content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content]
Run Code Online (Sandbox Code Playgroud)
Fel*_*ing 925
请参阅输入和输出:
with open('filename') as f:
lines = f.readlines()
Run Code Online (Sandbox Code Playgroud)
或者剥离换行符:
lines = [line.rstrip('\n') for line in open('filename')]
Run Code Online (Sandbox Code Playgroud)
编者注:这个答案的原始空白剥离命令,__CODE__
正如Janus Troelsen的评论所暗示的那样,将删除所有前导和尾随空格,而不仅仅是尾随空格__CODE__
.
rob*_*ert 543
这比必要的更明确,但做你想要的.
with open("file.txt", "r") as ins:
array = []
for line in ins:
array.append(line)
Run Code Online (Sandbox Code Playgroud)
Noc*_*wer 263
这将从文件中生成一行"数组".
lines = tuple(open(filename, 'r'))
Run Code Online (Sandbox Code Playgroud)
Ene*_*nso 188
如果你想要\n
包括:
with open(fname) as f:
content = f.readlines()
Run Code Online (Sandbox Code Playgroud)
如果你不想要\n
包括:
with open(fname) as f:
content = f.read().splitlines()
Run Code Online (Sandbox Code Playgroud)
Ped*_*ito 149
如果你不关心关闭文件,这个单线程工作:
with open('file.txt') as f:
my_list = list(f)
Run Code Online (Sandbox Code Playgroud)
在传统的方法:
with open('file.txt') as f:
lines = f.readlines()
Run Code Online (Sandbox Code Playgroud)
使用list
和with
(推荐):
lines = open('file.txt').readlines()
Run Code Online (Sandbox Code Playgroud)
Dev*_*ark 140
您可以简单地执行以下操作,如下所示:
with open('/your/path/file') as f:
my_lines = f.readlines()
Run Code Online (Sandbox Code Playgroud)
请注意,此方法有两个缺点:
1)您将所有行存储在内存中.在一般情况下,这是一个非常糟糕的主意.该文件可能非常大,您可能会耗尽内存.即使它不大,也只是浪费内存.
2)当你阅读它们时,这不允许处理每一行.因此,如果您在此之后处理您的行,则效率不高(需要两次通过而不是一次).
对于一般情况,更好的方法如下:
with open('/your/path/file') as f:
for line in f:
process(line)
Run Code Online (Sandbox Code Playgroud)
您可以以任何方式定义过程函数.例如:
def process(line):
if 'save the world' in line.lower():
superman.save_the_world()
Run Code Online (Sandbox Code Playgroud)
(Superman
课程的实施留给你练习).
这适用于任何文件大小,只需1遍即可浏览您的文件.这通常是通用解析器的工作方式.
Gio*_* PY 60
数据到列表中
假设我们有一个包含我们数据的文本文件,如下所示:
line 1
line 2
line 3
Run Code Online (Sandbox Code Playgroud)
python
并在解释器中写:>>> with open("myfile.txt", encoding="utf-8") as file:
... x = [l.strip() for l in file]
>>> x
['line 1','line 2','line 3']
Run Code Online (Sandbox Code Playgroud)
x = []
with open("myfile.txt") as file:
for l in file:
x.append(l.strip())
Run Code Online (Sandbox Code Playgroud)
>>> x = open("myfile.txt").read().splitlines()
>>> x
['line 1', 'line 2', 'line 3']
Run Code Online (Sandbox Code Playgroud)
>>> x = open("myfile.txt").readlines()
>>> x
['linea 1\n', 'line 2\n', 'line 3\n']
Run Code Online (Sandbox Code Playgroud)
>>> y = [x.rstrip() for x in open("my_file.txt")]
>>> y
['line 1','line 2','line 3']
with open('testodiprova.txt', 'r', encoding='utf-8') as file:
file = file.read().splitlines()
print(file)
with open('testodiprova.txt', 'r', encoding='utf-8') as file:
file = file.readlines()
print(file)
Run Code Online (Sandbox Code Playgroud)
MSe*_*ert 42
要将文件读入列表,您需要做三件事:
幸运的是,Python可以很容易地完成这些操作,因此将文件读入列表的最短方法是:
lst = list(open(filename))
Run Code Online (Sandbox Code Playgroud)
但是我会补充一些解释.
我假设你想打开一个特定的文件而你不直接处理文件句柄(或类似文件的句柄).在Python中打开文件最常用的函数是open
,它在Python 2.7中需要一个必需参数和两个可选参数:
文件名应该是表示文件路径的字符串.例如:
open('afile') # opens the file named afile in the current working directory
open('adir/afile') # relative path (relative to the current working directory)
open('C:/users/aname/afile') # absolute path (windows)
open('/usr/local/afile') # absolute path (linux)
Run Code Online (Sandbox Code Playgroud)
请注意,需要指定文件扩展名.这对Windows用户尤为重要,因为在浏览器中查看时,默认情况下会隐藏类似.txt
或.doc
等的文件扩展名.
第二个参数是mode
,它r
默认表示"只读".这正是您所需要的.
但是如果您确实想要创建文件和/或写入文件,则需要在此处使用不同的参数.如果您需要概述,有一个很好的答案.
要读取文件,您可以省略mode
或明确传递它:
open(filename)
open(filename, 'r')
Run Code Online (Sandbox Code Playgroud)
两者都将以只读模式打开文件.如果您想在Windows上读取二进制文件,则需要使用以下模式rb
:
open(filename, 'rb')
Run Code Online (Sandbox Code Playgroud)
在其他平台上,'b'
(二进制模式)被简单地忽略.
现在我已经展示了如何使用open
该文件,让我们再谈谈你总是需要close
它的事实.否则它将保持文件的打开文件句柄,直到进程退出(或Python使文件句柄变得无效).
虽然你可以使用:
f = open(filename)
# ... do stuff with f
f.close()
Run Code Online (Sandbox Code Playgroud)
当介于两者之间open
并close
抛出异常时,将无法关闭该文件.你可以通过使用try
和来避免这种情况finally
:
f = open(filename)
# nothing in between!
try:
# do stuff with f
finally:
f.close()
Run Code Online (Sandbox Code Playgroud)
但是Python提供上下文管理是有一个漂亮的语法(但open
它几乎等同于try
和finally
以上):
with open(filename) as f:
# do stuff with f
# The file is always closed after the with-scope ends.
Run Code Online (Sandbox Code Playgroud)
最后一种方法是在Python中打开文件的推荐方法!
好的,你已经打开了文件,现在该如何阅读?
该open
函数返回一个file
对象,它支持Pythons迭代协议.每次迭代都会给你一行:
with open(filename) as f:
for line in f:
print(line)
Run Code Online (Sandbox Code Playgroud)
这将打印文件的每一行.但请注意,每一行最后都会包含换行符\n
(您可能需要检查Python是否使用通用换行符支持构建- 否则您也可以\r\n
在Windows或\r
Mac上作为换行符).如果你不想要,你可以简单地删除最后一个字符(或Windows上的最后两个字符):
with open(filename) as f:
for line in f:
print(line[:-1])
Run Code Online (Sandbox Code Playgroud)
但是最后一行不一定有一个尾随换行符,所以不应该使用它.可以检查它是否以尾随换行结束,如果是,则删除它:
with open(filename) as f:
for line in f:
if line.endswith('\n'):
line = line[:-1]
print(line)
Run Code Online (Sandbox Code Playgroud)
但是你可以简单地\n
从字符串的末尾删除所有空格(包括字符),这也将删除所有其他尾随空格,因此如果这些很重要,你必须小心:
with open(filename) as f:
for line in f:
print(f.rstrip())
Run Code Online (Sandbox Code Playgroud)
但是,如果行结束\r\n
(Windows"换行符"),.rstrip()
也将照顾\r
!
既然您知道如何打开文件并阅读它,那么就可以将内容存储在列表中了.最简单的选择是使用该list
功能:
with open(filename) as f:
lst = list(f)
Run Code Online (Sandbox Code Playgroud)
如果您想要删除尾随换行符,则可以使用列表推导:
with open(filename) as f:
lst = [line.rstrip() for line in f]
Run Code Online (Sandbox Code Playgroud)
甚至更简单:默认情况下.readlines()
,file
对象的方法返回list
一行:
with open(filename) as f:
lst = f.readlines()
Run Code Online (Sandbox Code Playgroud)
这也将包括尾部换行符,如果你不想要它们,我会推荐这种[line.rstrip() for line in f]
方法,因为它避免保留两个包含内存中所有行的列表.
还有一个额外的选项来获得所需的输出,但它相当"次优":read
字符串中的完整文件然后拆分换行:
with open(filename) as f:
lst = f.read().split('\n')
Run Code Online (Sandbox Code Playgroud)
要么:
with open(filename) as f:
lst = f.read().splitlines()
Run Code Online (Sandbox Code Playgroud)
这些会自动处理尾随换行符,因为split
不包含该字符.但是它们并不理想,因为您将文件保存为字符串和内存中的行列表!
with open(...) as f
打开文件时使用,因为您不需要自己关闭文件,即使发生某些异常也会关闭文件.file
对象支持迭代协议,因此逐行读取文件非常简单for line in the_file_object:
.readlines()
但如果你想在将它们存储在列表中之前处理这些行,我会建议一个简单的列表理解.Joh*_*nny 41
将文件行读入列表的清洁和pythonic方式
首先,您应该专注于打开文件并以高效和pythonic的方式阅读其内容.以下是我个人不喜欢的方式示例:
infile = open('my_file.txt', 'r') # Open the file for reading.
data = infile.read() # Read the contents of the file.
infile.close() # Close the file since we're done using it.
Run Code Online (Sandbox Code Playgroud)
相反,我更喜欢以下打开文件进行读取和写入的方法,因为它非常干净,并且一旦完成使用它就不需要额外的步骤来关闭文件.在下面的语句中,我们打开文件进行读取,并将其分配给变量'infile'.一旦此语句中的代码运行完毕,该文件将自动关闭.
# Open the file for reading.
with open('my_file.txt', 'r') as infile:
data = infile.read() # Read the contents of the file into memory.
Run Code Online (Sandbox Code Playgroud)
现在我们需要专注于将这些数据放入Python列表中,因为它们是可迭代的,高效的和灵活的.在您的情况下,期望的目标是将文本文件的每一行放入单独的元素中.为此,我们将使用splitlines()方法,如下所示:
# Return a list of the lines, breaking at line boundaries.
my_list = data.splitlines()
Run Code Online (Sandbox Code Playgroud)
最终产品:
# Open the file for reading.
with open('my_file.txt', 'r') as infile:
data = infile.read() # Read the contents of the file into memory.
# Return a list of the lines, breaking at line boundaries.
my_list = data.splitlines()
Run Code Online (Sandbox Code Playgroud)
测试我们的代码:
A fost odatã ca-n povesti,
A fost ca niciodatã,
Din rude mãri împãrãtesti,
O prea frumoasã fatã.
Run Code Online (Sandbox Code Playgroud)
print my_list # Print the list.
# Print each line in the list.
for line in my_list:
print line
# Print the fourth element in this list.
print my_list[3]
Run Code Online (Sandbox Code Playgroud)
['A fost odat\xc3\xa3 ca-n povesti,', 'A fost ca niciodat\xc3\xa3,',
'Din rude m\xc3\xa3ri \xc3\xaemp\xc3\xa3r\xc3\xa3testi,', 'O prea
frumoas\xc3\xa3 fat\xc3\xa3.']
A fost odatã ca-n povesti, A fost ca niciodatã, Din rude mãri
împãrãtesti, O prea frumoasã fatã.
O prea frumoasã fatã.
Run Code Online (Sandbox Code Playgroud)
小智 29
这是通过对文件使用列表推导的另一个选项;
lines = [line.rstrip() for line in open('file.txt')]
Run Code Online (Sandbox Code Playgroud)
这应该是更有效的方式,因为大部分工作是在Python解释器内完成的.
ato*_*3ls 26
另一种选择是numpy.genfromtxt
,例如:
import numpy as np
data = np.genfromtxt("yourfile.dat",delimiter="\n")
Run Code Online (Sandbox Code Playgroud)
这将使data
NumPy数组具有与文件中一样多的行.
mol*_*ean 26
f = open("your_file.txt",'r')
out = f.readlines() # will append in the list out
Run Code Online (Sandbox Code Playgroud)
现在变量输出是你想要的列表(数组).你可以这样做:
for line in out:
print (line)
Run Code Online (Sandbox Code Playgroud)
要么
for line in f:
print (line)
Run Code Online (Sandbox Code Playgroud)
你会得到相同的结果.
Mar*_*oma 26
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Define data
lines = [' A first string ',
'A Unicode sample: €',
'German: äöüß']
# Write text file
with open('file.txt', 'w') as fp:
fp.write('\n'.join(lines))
# Read text file
with open('file.txt', 'r') as fp:
read_lines = fp.readlines()
read_lines = [line.rstrip('\n') for line in read_lines]
print(lines == read_lines)
Run Code Online (Sandbox Code Playgroud)
需要注意的事项:
with
是一个所谓的上下文管理器.它确保打开的文件再次关闭..strip()
或.rstrip()
将无法再现,lines
因为它们也剥离了白色空间..txt
对于您的应用程序,以下可能很重要:
另请参见:数据序列化格式的比较
如果您正在寻找一种制作配置文件的方法,您可能希望阅读我的简短文章Python中的配置文件.
oli*_*and 24
如果您想从命令行或stdin读取文件,还可以使用该fileinput
模块:
# reader.py
import fileinput
content = []
for line in fileinput.input():
content.append(line.strip())
fileinput.close()
Run Code Online (Sandbox Code Playgroud)
像这样传递文件:
$ python reader.py textfile.txt
Run Code Online (Sandbox Code Playgroud)
在这里阅读更多内容:http://docs.python.org/2/library/fileinput.html
Lan*_*are 23
在Python 3.4中引入,pathlib
有一个非常方便的从文件中读取文本的方法,如下所示:
from pathlib import Path
p = Path('my_text_file')
lines = p.read_text().splitlines()
Run Code Online (Sandbox Code Playgroud)
(该splitlines
调用将其从包含文件的全部内容的字符串转换为文件中的行列表).
pathlib
有很多方便的便利.read_text
很简洁,你不必担心打开和关闭文件.如果您只需要一次性读取文件,那么这是一个不错的选择.
Jea*_* T. 21
最简单的方法
一个简单的方法是:
在一行中,这将给出:
lines = open('C:/path/file.txt').read().splitlines()
Run Code Online (Sandbox Code Playgroud)
Abd*_*lal 15
只需使用splitlines()函数.这是一个例子.
inp = "file.txt"
data = open(inp)
dat = data.read()
lst = dat.splitlines()
print lst
# print(lst) # for python 3
Run Code Online (Sandbox Code Playgroud)
在输出中,您将获得行列表.
pam*_*bda 12
如果你想要面对一个非常大/巨大的文件并希望更快地阅读(想象你是在Topcoder/Hackerrank编码竞赛中),你可能会一次将更大的行读入内存缓冲区,而不是只是在文件级别逐行迭代.
buffersize = 2**16
with open(path) as f:
while True:
lines_buffer = f.readlines(buffersize)
if not lines_buffer:
break
for line in lines_buffer:
process(line)
Run Code Online (Sandbox Code Playgroud)
实现此目标的最简单方法是:
lines = list(open('filename'))
Run Code Online (Sandbox Code Playgroud)
要么
lines = tuple(open('filename'))
Run Code Online (Sandbox Code Playgroud)
要么
lines = set(open('filename'))
Run Code Online (Sandbox Code Playgroud)
在使用的情况下set
,必须记住,我们没有保留行顺序并摆脱了重复的行。
用这个:
import pandas as pd
data = pd.read_csv(filename) # You can also add parameters such as header, sep, etc.
array = data.values
Run Code Online (Sandbox Code Playgroud)
data
是数据框类型,并使用值获取ndarray。您还可以使用来获得列表array.tolist()
。
如果文档中也有空行,我喜欢读取内容并将其传递filter
以防止空字符串元素
with open(myFile, "r") as f:
excludeFileContent = list(filter(None, f.read().splitlines()))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3415289 次 |
最近记录: |