Python初学者:读写同一个文件

Python初学者:读写同一个文件,python,io,Python,Io,一周前开始使用Python,我有一些关于读写相同文件的问题要问。我在网上看过一些教程,但我仍然对此感到困惑。我能理解简单的读写文件 openFile = open("filepath", "r") readFile = openFile.read() print readFile openFile = open("filepath", "a") appendFile = openFile.write("\nTest 123") openFile.close() 但是,如果我尝试下面的方法

一周前开始使用Python,我有一些关于读写相同文件的问题要问。我在网上看过一些教程,但我仍然对此感到困惑。我能理解简单的读写文件

openFile = open("filepath", "r")
readFile = openFile.read()
print readFile 

openFile = open("filepath", "a")
appendFile = openFile.write("\nTest 123")

openFile.close()
但是,如果我尝试下面的方法,我会在正在编写的文本文件中得到一堆未知文本。有人能解释为什么我会出现这样的错误,为什么我不能用下面显示的方式使用相同的openFile对象吗

# I get an error when I use the codes below:       
openFile = open("filepath", "r+")
writeFile = openFile.write("Test abc")

readFile = openFile.read()
print readFile

openFile.close()
我将努力澄清我的问题。在上面的示例中,openFile是用于打开文件的对象。如果我想第一次给它写信,我没有问题。如果我想使用同一个openFile来读取文件或向其添加内容。它没有发生,或者给出了一个错误。我必须先声明相同/不同的open file对象,然后才能对同一文件执行另一个读/写操作

#I have no problems if I do this:    
openFile = open("filepath", "r+")
writeFile = openFile.write("Test abc")

openFile2 = open("filepath", "r+")
readFile = openFile2.read()
print readFile

openFile.close()

如果有人能告诉我我做错了什么,或者这只是一条蟒蛇,我将不胜感激。我正在使用Python 2.7。谢谢

读取和写入发生在当前文件指针所在的位置,每次读取/写入都会前进。 在您的特定情况下,写入
openFile
,会导致文件指针指向文件的结尾。试图从末尾读取将导致EOF。
您需要重置文件指针,通过
seek(0)
指向文件的开头,然后再从中读取更新的响应

这似乎是Windows特有的bug-

引用在中解释的变通方法

在打开进行更新的文件上混合读取和写入的效果是 完全未定义,除非在 它们(例如,seek())。我猜不出是什么 你期待着发生,但似乎最有可能的是你所期待的 可以通过插入

fp.seek(fp.tell())

在read()和write()之间

我最初的回答演示了如何在同一个文件上读/写以进行附加。如果您使用的是Windows,则显然不是这样

原始响应

在“r+”模式下,使用write方法将根据指针所在的位置将字符串对象写入文件。在您的情况下,它会将字符串“testabc”附加到文件的开头。请参见下面的示例:

>>> f=open("a","r+")
>>> f.read()
'Test abc\nfasdfafasdfa\nsdfgsd\n'
>>> f.write("foooooooooooooo")
>>> f.close()
>>> f=open("a","r+")
>>> f.read()
'Test abc\nfasdfafasdfa\nsdfgsd\nfoooooooooooooo'
字符串“fooooo”被追加到文件的末尾,因为指针已经在文件的末尾

您使用的是区分二进制文件和文本文件的系统吗?在这种情况下,您可能希望使用“rb+”作为模式

在系统上,将“b”附加到模式以二进制模式打开文件 区分二进制文件和文本文件;在系统上 没有这种区别,添加“b”没有效果。


每个打开的文件都有一个隐式指针,指示数据的读取和写入位置。通常这默认为文件的开头,但如果使用
a
(append)模式,则默认为文件的结尾。还值得注意的是,
w
模式将截断您的文件(即删除所有内容),即使您将
+
添加到该模式

无论何时读取或写入N个字符,读/写指针都会在文件中向前移动该数量。如果你还记得的话,我觉得把它想象成一盘旧的盒式磁带是有帮助的。因此,如果执行以下代码:

fd = open("testfile.txt", "w+")
fd.write("This is a test file.\n")
fd.close()

fd = open("testfile.txt", "r+")
print fd.read(4)
fd.write(" IS")
fd.close()
。。。它应该最后打印
这个
,然后将文件内容保留为
这是一个测试文件。
。这是因为初始的
read(4)
返回文件的前4个字符,因为指针位于文件的开头。它将指针留在
之后的空格字符上,因此下面的
写入(“IS”)
将用空格(与前面的空格相同)覆盖接下来的三个字符,后跟
IS
,替换现有的
IS

您可以使用文件的
seek()
方法跳转到特定点。在上述示例之后,如果执行以下操作:

fd = open("testfile.txt", "r+")
fd.seek(10)
fd.write("TEST")
fd.close()
。。。然后您会发现该文件现在包含
这是一个测试文件。

所有这些都适用于Unix系统,您可以测试这些示例以确保。但是,我在Windows系统上混合使用
read()
write()
时遇到了问题。例如,当我在Windows计算机上执行第一个示例时,它会正确地打印
,但当我随后检查文件时,
write()
被完全忽略。但是,第二个示例(使用
seek()
)似乎在Windows上运行良好

总之,如果您想在Windows中从文件的中间读/写,我建议始终使用显式的
seek()
,而不是依赖读/写指针的位置。如果你只做读或写,那么它是相当安全的

最后一点-如果要将Windows上的路径指定为文字字符串,请记住转义反斜杠:

fd = open("C:\\Users\\johndoe\\Desktop\\testfile.txt", "r+")
或者,您可以通过在开始处放置
r
来使用原始字符串:

fd = open(r"C:\Users\johndoe\Desktop\testfile.txt", "r+")
或者,最可移植的选项是使用
os.path.join()


您可以在中找到有关文件IO的更多信息。

您可以用python读取、修改和保存同一文件,但实际上您必须替换文件中的全部内容,并在更新文件内容之前调用:

# set the pointer to the beginning of the file in order to rewrite the content
edit_file.seek(0)
我需要一个函数来遍历文件夹的所有子目录,并根据一些标准编辑文件的内容,如果它有帮助的话:

new_file_content = ""
for directories, subdirectories, files in os.walk(folder_path):
    for file_name in files:
        file_path = os.path.join(directories, file_name)
        # open file for reading and writing
        with io.open(file_path, "r+", encoding="utf-8") as edit_file:
            for current_line in edit_file:
                if condition in current_line:
                    # update current line
                    current_line = current_line.replace('john', 'jack')
                new_file_content += current_line
            # set the pointer to the beginning of the file in order to rewrite the content
            edit_file.seek(0)
            # delete actual file content
            edit_file.truncate()
            # rewrite updated file content
            edit_file.write(new_file_content)
            # empties new content in order to set for next iteration
            new_file_content = ""
            edit_file.close()

这就是奇怪的部分。如果我尝试这些行,似乎会出现错误:f=open(“C:\Users\MooMoo\Desktop\costs.txt”,“r+”)print f.read()f.write(“foooooooo”)。我收到的错误消息:回溯(最近一次调用):文件“C:\Users\MooMoo\Desktop\Python27\PyProject\src\test.py”,第43行,f.write(“fooooooo”)IOError:[Errno 0]error f.close(),这似乎是一个Windows指定的
new_file_content = ""
for directories, subdirectories, files in os.walk(folder_path):
    for file_name in files:
        file_path = os.path.join(directories, file_name)
        # open file for reading and writing
        with io.open(file_path, "r+", encoding="utf-8") as edit_file:
            for current_line in edit_file:
                if condition in current_line:
                    # update current line
                    current_line = current_line.replace('john', 'jack')
                new_file_content += current_line
            # set the pointer to the beginning of the file in order to rewrite the content
            edit_file.seek(0)
            # delete actual file content
            edit_file.truncate()
            # rewrite updated file content
            edit_file.write(new_file_content)
            # empties new content in order to set for next iteration
            new_file_content = ""
            edit_file.close()