简体   繁体   English

关于python编写文件的问题

[英]Problem about python writing files

I've got a weird problem with python programming. 我在python编程中遇到了一个奇怪的问题。 I used the statement'writelines()' to write a series of lists into a new file.During the process I could see the context in the file icon via preview, however once after the program finished running the output file comes out to be a blank file. 我使用'writelines()'语句将一系列列表写入新文件。在此过程中,我可以通过预览在文件图标中看到上下文,但是在程序完成运行输出文件后,空白文件。

In short, my problem is that the program doesn't have any output but a blank file. 简而言之,我的问题是该程序没有任何输出,但是有一个空白文件。

Here's the code: 这是代码:

infile=open('/Users/Jim/Desktop/py/result.txt','r')
outfile=open('/Users/Jim/Desktop/py/output.txt','a')
line=infile.readline()
i=1
while(line):
    check=str(i)+':'
    if line.startswith(check):
        i+=1
        block=[infile.readline() for j in range(1,7)]
        judge=block[1].split()
        for j in judge:
            if j=='stem' or j=='differetiation' or j=='differetiating':
                outfile.write(str(i)+':\n')
                outfile.writelines(block)    #check if the paragraph has the given key words, if true then write the paragraph into the output file.
                break
    line=infile.readline()
outfile.close()
infile.close()

Some additional information if helpful: The python version is 2.6.3, and the os is Mac OS 10.6. 如果有帮助,请提供一些其他信息:python版本是2.6.3,而os是Mac OS 10.6。

I guess it's caused by incorrect indentation. 我猜这是由于缩进不正确造成的。 The break statement should be inside the if block. break语句应位于if块内。 The loop as it is written will only try the first option from judge . 编写的循环将仅尝试judge的第一个选择。 Check if you don't have mixed spaces and tabs in the file. 检查文件中是否没有混合的空格和制表符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM