[英]Read files with fileinput.input() from X line
here my question, it is probably not very complex but I am learning Python. 这是我的问题,可能不是很复杂,但是我正在学习Python。 I'm trying to read multiple files (all of them with the same format), at the same time a have to begin reading them from line 32, somehow I don't find the most efficient way to do so.
我正在尝试读取多个文件(所有文件都使用相同的格式),同时必须从第32行开始读取它们,以某种方式,我找不到最有效的方法。
Here my code until now: 到目前为止,这里是我的代码:
for file in fileinput.input():
entries = [f.strip().split("\t") for f in file].readlines()[32:]
which gives the error: AttributeError: 'list' object has no attribute 'readlines' 出现错误:AttributeError:'list'对象没有属性'readlines'
I know another possibility would be: 我知道另一种可能性是:
sources = open(sys.argv[1], "r").readlines()[32:]
and then just on the command line python3.2 script.py data/*.csv. 然后在命令行python3.2 script.py data / *。csv上。 But this seems not to work properly.
但这似乎无法正常工作。
I am thanked for any help. 感谢您的帮助。
It's just a little syntax 这只是一点语法
entries = [f.strip().split("\t") for f in file].readlines()[32:]
should be: 应该:
entries = [f.strip().split("\t") for f in file.readlines()][32:]
You can use openhook
argument. 您可以使用
openhook
参数。
According to the module documentation : 根据模块文档 :
You can control how files are opened by providing an opening hook via the openhook parameter to
fileinput.input()
orFileInput()
.您可以通过使用openhook参数将打开挂钩提供给
fileinput.input()
或FileInput()
来控制文件的打开方式。 The hook must be a function that takes two arguments, filename and mode, and returns an accordingly opened file-like object.该挂钩必须是一个接受两个参数(文件名和模式)并返回相应打开的类似文件的对象的函数。 Two useful hooks are already provided by this module.
该模块已经提供了两个有用的钩子。
import fileinput
def skip32(filename, mode):
f = open(filename, mode)
for i in range(32):
f.readline()
return f
entries = [line.strip().split('\t') for line in fileinput.input(openhook=skip32)]
BTW, the last line can be replaced with (using csv
module): 顺便说一句,最后一行可以替换为(使用
csv
模块):
import csv
entries = list(csv.reader(fileinput.input(openhook=skip32), delimiter='\t'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.