当从Python中的函数接收文件时(迭代后),指向该行的指针会发生更改

2024-04-26 02:51:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我将一个文件传递给一个函数并对其进行迭代。 取回文件后,我的指针被更改。我想这是因为我将其作为引用传递。我如何避免它并将其作为“值”传递。我浏览了StackoverFlow中的其他示例,其中大多数只讨论了一个场景(list.append)。这是我的密码:

传递文件的代码:

data = matchpattern(infile , record_read_regex , output_fmt)

for currentline in infile:
#Following line prints the line with pointer shifted ( requirement is to print the first line of the list
  print 'printing the first line of the list in calling function********* ' + currentline 

功能:

def matchpattern(infiles , record_read_regex, output_fmt):
  for line in infiles:
    #Following line prints the first line of the list
    print 'printing the first line in pattern function ' +  line
    m = re.match(record_read_regex, line)
    if m:
      return record_capture

Tags: 文件oftheinreadoutputlinerecord
1条回答
网友
1楼 · 发布于 2024-04-26 02:51:50

读取文件会消耗数据,这不一定是可逆操作。但是,磁盘文件通常为seekable,这允许您在保存时恢复位置:

oldpos = infile.tell()
callfunction(infile)
infile.seek(oldpos)

一个文件可能会在读数之间发生变化,而管道、插座、设备等首先是不可查找的。在某些情况下,搜索本身需要很长时间

相关问题 更多 >

    热门问题