Jim
Jim

Reputation: 27

Problem about python writing files

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.

Upvotes: 0

Views: 453

Answers (1)

Lukáš Lalinský
Lukáš Lalinský

Reputation: 41306

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.

Upvotes: 2

Related Questions