PeanutsMonkey
PeanutsMonkey

Reputation: 7095

Why does my Python code add additional characters when writing and reading a file

I am just learning how to code in Python and have not been able to find a solution or answer as to why when I attempt to read a file that has just been written to it bears additional characters.

Code

#-*-coding:utf-8-*-
from sys import argv
from os.path import exists

script, source, copy = argv

print "We'll be opening, reading, writing to and closing a file"
opensource = open(source)
readsource = opensource.read()
print readsource
print "Great. We opened and read file"

opencopy = open(copy, 'w+') #we want to write and read file
opencopy.write(readsource) #copy the contents of the source file
opencopy.read()


opensource.close()
opencopy.close()

Output

enter image description here

Contents

test    °D                                                                                                               ΃ ø U     ø U     ` 6    ` 6     0M     Ð                

I am running version 2.7 of Python on Windows 7 Professional 64bit.

Upvotes: 1

Views: 138

Answers (1)

Anthon
Anthon

Reputation: 76568

This seems to be a Windows issue with reading a file opened with "w+" directly after a write. Start with adding two print statements like this:

opencopy.write(readsource) #copy the contents of the source file
print opencopy.tell()
opencopy.read()
print opencopy.tell()

And run this on a file with only as contents the words 'test' + CR + LF, you get as output:

We'll be opening, reading, writing to and closing a file
test

Great. We opened and read file
6
4098

(If you do the same under Linux, the read does not work beyond the end of the file (and you get two times the value 6 from opencopy.tell().)

What you probably want to do is:

print opencopy.tell()
opencopy.seek(0)
print opencopy.tell()
opencopy.read()
print opencopy.tell()

You then get 6 and 6 as output from tell(). Now this results in reading the word 'test', that you just wrote.

If you do not want to read what you just wrote, put opencopy.flush() between the read and the write statement:

opencopy.write(readsource) #copy the contents of the source file
print opencopy.tell()
opencopy.flush()
opencopy.read()
print opencopy.tell()

Upvotes: 1

Related Questions