python写文件的问题
我在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我猜这是由不正确的缩进引起的。
break
语句应位于if
块内。编写的循环只会尝试judge
中的第一个选项。检查文件中是否没有混合空格和制表符。I guess it's caused by incorrect indentation. The
break
statement should be inside theif
block. The loop as it is written will only try the first option fromjudge
. Check if you don't have mixed spaces and tabs in the file.