2012-11-29 30 views
1

我刚刚学习如何使用Python进行编码,并且无法找到解决方案或答案,因为当我尝试读取刚才被写入它附带额外的字符。为什么我的Python代码在写入和读取文件时添加了额外的字符

代码

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

输出

enter image description here

内容

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

我在Windows 7 Professional 64bit上运行Python 2.7版本。

回答

1

这似乎是一个Windows问题,在写入后直接读取用“w +”打开的文件。 与添加两条print语句像这样开始:

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

的文件并只为内容的话“测试” + CR + LF运行它,你会得到作为输出:

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

Great. We opened and read file 
6 
4098 

(如果你在Linux下一样,读不超出文件的工作进行到底(和你opencopy.tell()得到的值6的两倍。)

你可能想要做的是:

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

然后,您将得到6和6作为tell()的输出。现在,这会导致您阅读“测试”一词,即您刚刚写的 。

如果你不想读什么,你只是写,把opencopy.flush()读取和写入的语句之间:

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