1

我只是在学习如何在 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()

输出

在此处输入图像描述

内容

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

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

4

1 回答 1

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() 获得值 6 的两倍。)

您可能想要做的是:

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

然后你得到 6 和 6 作为tell() 的输出。现在这将导致读取您刚刚编写的单词“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()
于 2013-02-21T13:35:06.577 回答