python写文件的问题

发布于 2024-08-07 03:47:27 字数 915 浏览 1 评论 0原文

我在 python 编程中遇到了一个奇怪的问题。我使用语句“writelines()”将一系列列表写入一个新文件。在这个过程中,我可以通过预览看到文件图标中的上下文,但是一旦程序完成运行后,输出文件就会变成一个空白文件。

简而言之,我的问题是该程序没有任何输出,只有一个空白文件。

这是代码:

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()

一些附加信息(如果有帮助): python版本是2.6.3,操作系统是Mac OS 10.6。

I've got a weird problem with python programming. 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.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

醉殇 2024-08-14 03:47:27

我猜这是由不正确的缩进引起的。 break 语句应位于 if 块内。编写的循环只会尝试 judge 中的第一个选项。检查文件中是否没有混合空格和制表符。

I guess it's caused by incorrect indentation. The break statement should be inside the if block. The loop as it is written will only try the first option from judge. Check if you don't have mixed spaces and tabs in the file.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文