Python 2.7 为什么我的Python代码在写入和读取文件时会添加额外的字符

Python 2.7 为什么我的Python代码在写入和读取文件时会添加额外的字符,python-2.7,Python 2.7,我只是在学习如何用Python编写代码,还没有找到一个解决方案或答案来解释为什么当我试图读取一个刚刚写入的文件时,它会带有额外的字符 代码 输出 内容 我正在Windows7 Professional上运行Python的2.7版64位。

我只是在学习如何用Python编写代码,还没有找到一个解决方案或答案来解释为什么当我试图读取一个刚刚写入的文件时,它会带有额外的字符

代码

输出

内容


我正在Windows7 Professional上运行Python的2.7版64位。 这似乎是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()
然后从tell()得到6和6作为输出 你刚刚写的

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

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

这似乎是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()
然后从tell()得到6和6作为输出 你刚刚写的

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

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