在 Python 2.5 中,我正在使用文件指针读取结构化文本数据文件(大小约为 30 MB):
fp = open('myfile.txt', 'r')
line = fp.readline()
# ... many other fp.readline() processing steps, which
# are used in different contexts to read the structures
但是,在解析文件时,我遇到了一些有趣的事情,我想报告其行号,以便我可以调查文本编辑器中的文件。我可以使用fp.tell()
告诉我字节偏移量在哪里(例如16548974L
),但是没有“fp.tell_line_number()”来帮助我翻译这是一个行号。
是否有Python内置或扩展可以轻松跟踪和“告诉”文本文件指针所在的行号?
注意:我不问< /a> 使用 line_number += 1
样式计数器,因为我在不同的上下文中调用 fp.readline()
,这种方法需要更多的调试,而不是值得的将计数器插入右角的代码。
In Python 2.5, I am reading a structured text data file (~30 MB in size) using a file pointer:
fp = open('myfile.txt', 'r')
line = fp.readline()
# ... many other fp.readline() processing steps, which
# are used in different contexts to read the structures
But then, while parsing the file, I hit something interesting that I want to report the line number of, so I can investigate the file in a text editor. I can use fp.tell()
to tell me where the byte offset is (e.g. 16548974L
), but there is no "fp.tell_line_number()" to help me translate this to a line number.
Is there either a Python built-in or extension to easily track and "tell" what line number a text file pointer is on?
Note: I'm not asking to use a line_number += 1
style counter, as I call fp.readline()
in different contexts and that approach would require more debugging than it is worth to insert the counter in the right corners of the code.
发布评论
评论(9)
此问题的典型解决方案是定义一个新类来包装
file
的现有实例,该实例会自动计算数字。像这样的东西(就在我的脑海中,我还没有测试过这个):像这样使用它:
它看起来像标准模块
fileinput
做同样的事情(以及其他一些事情);如果你愿意的话,你可以用它来代替。A typical solution to this problem is to define a new class that wraps an existing instance of a
file
, which automatically counts the numbers. Something like this (just off the top of my head, I haven't tested this):Use it like this:
It looks like the standard module
fileinput
does much the same thing (and some other things as well); you could use that instead if you like.您可能会发现
fileinput
模块很有用。它提供了一个通用接口,用于迭代任意数量的文件。文档中的一些相关亮点:You might find the
fileinput
module useful. It provides a generalized interface for iterating over an arbitrary number of files. Some relevant highlights from the docs:以下代码将在遍历文件('testfile')时打印行号(指针当前所在的位置)
输出:
The following code will print the line number(where the pointer is currently on) while traversing through the file('testfile')
output:
我不这么认为,不是以您想要的方式(如
open
返回的 Python 文件句柄的标准内置功能)。如果您在阅读行或使用包装类时不适合手动跟踪行号(顺便说一句,GregH 和 senderle 提出了很好的建议),那么我认为您只需使用
fp.tell()
计算并返回到文件的开头,阅读直到到达那里。这并不是一个太糟糕的选择,因为我假设错误条件比一切顺利运行的可能性要小。如果一切正常,就没有影响。
如果出现错误,则您需要花费额外的精力来重新扫描文件。如果文件很大,可能会影响您感知的性能 - 如果这是一个问题,您应该考虑到这一点。
I don't think so, not in the way you desire (as in a standard built-in feature of Python file handles returned by
open
).If you're not amenable to tracking the line number manually as you read the lines or the use of a wrapper class (excellent suggestions by GregH and senderle, by the way), then I think you'll have to simply use the
fp.tell()
figure and go back to the start of the file, reading until you get there.That's not too bad an option since I'm assuming error conditions will be less likely than everything working swimmingly. If everything works okay, there's no impact.
If there's an error, then you have the extra effort of rescanning the file. If the file is big, that may impact your perceived performance - you should take that into account if it's a problem.
使用
with
上下文管理器打开文件并枚举for
循环中的行。Open file using
with
context manager and enumerate lines in afor
loop.一种方法可能是迭代该行并保留已看到的行数的显式计数:
One way might be to iterate over the line and keep an explicit count of the number of lines already seen:
以下代码创建一个函数 Which_Line_for_Position(pos),它给出位置 pos 的行号,也就是说 文件中位置 pos 处的字符所在的行数。
该函数可以与任何位置作为参数一起使用,独立于文件指针当前位置的值以及调用该函数之前该指针的移动历史记录。
因此,使用此函数,我们不限于仅在行上不间断迭代期间确定当前行的编号,就像 Greg Hewgill 的解决方案的情况一样。
。
可以借助模块 fileinput 编写相同的解决方案:
但是此解决方案有一些不便:
。
示例:
结果
。
然后,有了函数 Which_Line_for_Position() ,就很容易获得当前行的编号:只需将 f.tell() 作为参数传递给函数
但是 警告:当使用f.tell()并在文件中移动文件指针时,绝对有必要以二进制模式打开文件:'rb' 或'rb+' 或 'ab' 或 ....
The following code creates a function Which_Line_for_Position(pos) that gives the number of the line for the position pos, that is to say the number of line in which lies the character situated at position pos in the file.
This function can be used with any position as argument, independantly from the value of the file's pointer's current position and from the historic of the movements of this pointer before the function is called.
So, with this function, one isn't limited to determine the number of the current line only during an uninterrupted iteration on the lines, as it is the case with Greg Hewgill's solution.
.
The same solution can be written with the help of the module fileinput:
But this solution has some inconveniences:
.
exemple:
result
.
Then, having function Which_Line_for_Position() , it is easy to obtain the number of a current line : just passing f.tell() as argument to the function
But WARNING: when using f.tell() and doing movements of the file's pointer in the file, it is absolutely necessary that the file is opened in binary mode: 'rb' or 'rb+' or 'ab' or ....
最近在解决类似的问题并提出了这个基于类的解决方案。
将
print_line_mod_number
属性设置为您想要记录的节奏,然后调用processFile
。例如...如果您想要每 100 行反馈一次,它看起来像这样。
控制台输出将是
Messing around with a similar problem recently and came up with this class based solution.
Set the
print_line_mod_number
property to the cadence you want logged and then callprocessFile
.For example... if you want feedback every 100 lines it would look like this.
The console output would be
关于 @eyquem 的解决方案,我建议将
mode='r'
与 fileinput 模块一起使用和 fileinput.lineno() 选项,它对我有用。以下是我在代码中实现这些选项的方法。
Regarding the solution by @eyquem, I suggest using
mode='r'
with the fileinput module andfileinput.lineno()
option and it has worked for me.Here is how I am implementing these options in my code.