为什么我的Python代码在编写和读取文件时会添加其他字符

时间:2012-11-29 00:49:14

标签: python-2.7

我正在学习如何使用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上运行2.7版本的Python。

1 个答案:

答案 0 :(得分:1)

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

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

并在一个文件中运行,只有内容为'test'+ 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()得到两倍的值。)

您可能想要做的是:

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

然后从tell()得到6和6作为输出。现在这导致读取'test'这个词 你刚才写的。

如果您不想阅读刚写的内容,请将opencopy.flush()放在read和write语句之间:

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