Python为什么无法读取包含内容的文件?
Python why file with content cannot be read?
import pathlib
file_name = '%s/survey_ids.txt' % pathlib.Path(__file__).parent.resolve()
f = open(file_name, "a+")
f.write("hello world\n")
print(f.read())
f.close()
我第一次 运行 脚本时,它会创建文件 survey_ids.txt
并将 hello world\n
写入其中。它肯定不会打印任何东西。但是我第二次 运行 它,它写了另一个 hello world\n
到 survey_ids.txt
但仍然没有打印任何东西。我想它会打印 hello world\n
。为什么会这样?
f.write
提高流位置。因此,当您使用 f.read()
读取文件时,它将尝试从当前流位置读取到文件末尾。
要获得预期的行为,请尝试在 .read
调用之前 seek
到字节偏移量 0。
f = open("test.txt", "a+")
f.write("hello world\n")
f.seek(0)
print(f.read())
f.close()
另外如评论中所推荐的那样更好to use context managers它会自动清理资源。
当您使用a+
模式打开文件时,文件流将位于文件末尾。在创建 DictReader 之前调用 f.seek( 0 )
,其中 f 是使用 open( ... )
创建的文件对象。有关此问题的更详细讨论,请参阅 。
f = open("test.txt", "a+")
f.write("hello world\n")
f.seek(0)
print(f.read())
f.close()
并用于打开
with open(file_name, "a+") as f:
f.write("hello world\n")
f.seek(0)
print(f.read())
import pathlib
file_name = '%s/survey_ids.txt' % pathlib.Path(__file__).parent.resolve()
f = open(file_name, "a+")
f.write("hello world\n")
print(f.read())
f.close()
我第一次 运行 脚本时,它会创建文件 survey_ids.txt
并将 hello world\n
写入其中。它肯定不会打印任何东西。但是我第二次 运行 它,它写了另一个 hello world\n
到 survey_ids.txt
但仍然没有打印任何东西。我想它会打印 hello world\n
。为什么会这样?
f.write
提高流位置。因此,当您使用 f.read()
读取文件时,它将尝试从当前流位置读取到文件末尾。
要获得预期的行为,请尝试在 .read
调用之前 seek
到字节偏移量 0。
f = open("test.txt", "a+")
f.write("hello world\n")
f.seek(0)
print(f.read())
f.close()
另外如评论中所推荐的那样更好to use context managers它会自动清理资源。
当您使用a+
模式打开文件时,文件流将位于文件末尾。在创建 DictReader 之前调用 f.seek( 0 )
,其中 f 是使用 open( ... )
创建的文件对象。有关此问题的更详细讨论,请参阅
f = open("test.txt", "a+")
f.write("hello world\n")
f.seek(0)
print(f.read())
f.close()
并用于打开
with open(file_name, "a+") as f:
f.write("hello world\n")
f.seek(0)
print(f.read())