简体   繁体   中英

Writing to file gives only new line on first execution

First time I execute this program, the resulting file does not have anything in it besides a new line. But the second time I execute it, it writes to 'out.txt' correctly, but the new line from the first execution is still there. Why does it not work correctly the first time?

bhaarat = open('bhaarat.txt', 'r+')
bhaarat_read = bhaarat.read()

out = open('out.txt', 'r+')
out_read = out.read()

bhaarat_split = bhaarat_read.split()

for word in bhaarat_split:
    if word.startswith('S') or word.startswith('H'):
        out.write(word + "\n")

bhaarat.write('\n23. English\n')
print out_read
print bhaarat_read

bhaarat.close()
out.close()

This is a problem with Windows. The workaround ( see python mailing list ) is to use

f.seek(f.tell())

between calls to read() and write() on a file f that was opened with one of the + options.

Adapted to your problem you have to call bhaarat.seek(bhaarat.tell()) after first reading the file with bhaarat_read = bhaarat.read() and before writing to it with bhaarat.write('\\n23. English\\n') . The same for your out .

In Python3 this problem is fixed, so one more reason to switch :)


EDIT The following code works for me. The files bhaarat.txt and out.txt must both be present.

bhaarat = open('bhaarat.txt', 'r+')
bhaarat_read = bhaarat.read()
bhaarat.seek(bhaarat.tell())
out = open('out.txt', 'r+')
out_read = out.read()
out.seek(out.tell())
bhaarat_split = bhaarat_read.split()

for word in bhaarat_split:
    if word.startswith('S') or word.startswith('H'):
        out.write(word + "\n")

bhaarat.write('\n23. English\n')
print out_read
print bhaarat_read

bhaarat.close()
out.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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