将文本文件中的特定行读入Python变量?
我有很多文本文件,布局如下将文本文件中的特定行读入Python变量?,python,Python,我有很多文本文件,布局如下 heading subheading info1 info2 info3 其中,每行的字符数将因文件而异。对于每个文件,我希望将第2行存储为Python变量 我可以将整个文件加载到一个变量中 with open('data.txt', 'r') as myfile: data=myfile.read().replace('\n', '') 但是我不确定如何指定只读第2行。您可以使用readline功能一次读取一行: with open('data.txt'
heading
subheading
info1
info2
info3
其中,每行的字符数将因文件而异。对于每个文件,我希望将第2行存储为Python变量
我可以将整个文件加载到一个变量中
with open('data.txt', 'r') as myfile:
data=myfile.read().replace('\n', '')
但是我不确定如何指定只读第2行。您可以使用
readline
功能一次读取一行:
with open('data.txt', 'r') as myfile:
line1=myfile.readline()
data=myfile.readline().replace('\n', '')
对于某些任意行,您可以迭代文件,直到到达该行:
with open('data.txt', 'r') as myfile:
dataline = 4 # any number less than or equal to the number of lines in the file
for line in range(dataline - 1):
myfile.readline()
data=myfile.readline().replace('\n', '')
您可以使用
readline
功能一次读取一行:
with open('data.txt', 'r') as myfile:
line1=myfile.readline()
data=myfile.readline().replace('\n', '')
对于某些任意行,您可以迭代文件,直到到达该行:
with open('data.txt', 'r') as myfile:
dataline = 4 # any number less than or equal to the number of lines in the file
for line in range(dataline - 1):
myfile.readline()
data=myfile.readline().replace('\n', '')
您不需要读取整个文件,只需读取所需行之前的行即可。最简单的方法是使用
itertools
模块
with open('data.txt', 'r') as myfile:
data = next(itertools.islice(myfile, 1, None))
切片通过iterablemyfile
的结尾生成元素1(元素0是第一行)next
只需从该表生成下一个可用项,即第2行
(我不知道副本中有
linecache
模块;这是解决当前问题的更好方法。)您不需要读取整个文件,只需读取所需行之前的行。最简单的方法是使用itertools
模块
with open('data.txt', 'r') as myfile:
data = next(itertools.islice(myfile, 1, None))
切片通过iterablemyfile
的结尾生成元素1(元素0是第一行)next
只需从该表生成下一个可用项,即第2行
(我不知道副本中的
linecache
模块;这是解决眼前问题的更好的解决方案。)Mmm,这是一个有点硬编码的解决方案;如果OP想要第50条线呢?说得对。为任意行更新。嗯,这是一个硬编码的解决方案;如果OP想要第50条线呢?说得对。为任意行更新。对于通用数据处理,请查看pandas
对于通用数据处理,请查看pandas
是的,这非常完美。谢谢,这太完美了。谢谢