文件指针 - 在函数

时间:2017-06-28 04:19:54

标签: python pointers parameters reference

Python 2.7 从以下网址下载测试文件:www.py4inf.com/code/mbox.txt
简而言之,我需要列出以' From'开头的所有行。并只采取邮件地址。逐行选择。
如果条件为真,则在(仅)邮件地址(结果)中写入其他文件。我可以编写代码并且它正在工作。但是如果我使用函数会更好。当我试图传递参数时,我崩溃了。当我有一个接收参数并发送一个或两个参数的函数时,我遇到了问题。

结果是:逐行复制输出文件中的ALL输入文件,几乎就像递归一样。没有搜索,文件非常大。

最后,请您阅读有关功能,参数,传递参数,传递参考等内容的任何页面。问问很简单,我更喜欢阅读并尝试理解,如果我有问题,请在半夜点亮一个坎德!。

#Li is the input paramet. Line from fileRead(the pointer of the file).  
#if the condition is true select all lines that start with From:

def funFormat(li):
if li.startswith('From:'):
    li = li.rstrip('')
    li = li.replace('From: ',' \n')
    return li?

fileRead=open('mbox_small.txt','r')
for eachline in fileRead:
    result=funFormat(eachline)
    fileWrite =open('Resul73.txt', 'a')
    fileWrite.write( result )
fileRead.close()
fileWrite.close()

1 个答案:

答案 0 :(得分:0)

每次需要编写时都会打开一个文件,并在最后关闭它。也许这就是弄乱了什么?试试这个,让我知道它是否有效 -

#Li is the input paramet. Line from fileRead(the pointer of the file).  
#if the condition is true select all lines that start with From:

def funFormat(li):
    if li.startswith('From:'):
        li = li.rstrip('')
        li = li.replace('From: ',' \n')
        return li
    else:
        return None

fileRead = open('mbox_small.txt', 'r')
fileWrite = open('Resul73.txt', 'a')
for eachline in fileRead:
    result=funFormat (eachline)
    if result:
        fileWrite.write (result)
fileRead.close()
fileWrite.close()

另外,我建议你阅读有关块的内容。这将有助于您更有效地处理文件。至于功能,网上有足够的资源。

相关问题