有没有一种方法可以使用Python读取和写入文件夹中的多个文本文件?
我正试图从一个文件夹中检索几个文本文件。之后,我尝试读取目录中的所有文件,然后在每个文件的顶部添加一个空行 然而,一旦我运行程序,它就不会执行我想要的。代码如下:有没有一种方法可以使用Python读取和写入文件夹中的多个文本文件?,python,Python,我正试图从一个文件夹中检索几个文本文件。之后,我尝试读取目录中的所有文件,然后在每个文件的顶部添加一个空行 然而,一旦我运行程序,它就不会执行我想要的。代码如下: import os folderPath = "./textFiles" def myFilesAddEmptyLine(): for file in os.listdir(folderPath): if file.endswith(".txt"): with open(file,
import os
folderPath = "./textFiles"
def myFilesAddEmptyLine():
for file in os.listdir(folderPath):
if file.endswith(".txt"):
with open(file, "r+") as myFile:
# print(myFile)
# ^ This returns "<_io.TextIOWrapper name='test.txt' mode='r+' encoding='cp1252'>" in the console.
fileContent = myFile.read()
myFile.seek(0, 0)
myFile.write("\n" + fileContent)
myFilesAddEmptyLine()
有谁能简要介绍一下第一段代码的问题是什么?提前谢谢 正如user@asylumax在评论中指出的那样:
import os
folderPath = "./textFiles"
def myFilesAddEmptyLine():
for file in os.listdir(folderPath):
if file.endswith(".txt"):
with open(file, "r+") as myFile:
fileContent = myFile.read()
myFile.seek(0, 0)
myFile.write("\n" + fileContent)
myFilesAddEmptyLine()
需要更改为:
import os
folderPath = "./textFiles"
def myFilesAddEmptyLine():
for file in os.listdir(folderPath):
if file.endswith(".txt"):
with open(os.path.join(folderPath, file), "r+") as myFile: #This is the line that needed changing.
fileContent = myFile.read()
myFile.seek(0, 0)
myFile.write("\n" + fileContent)
print(myFile)
myFilesAddEmptyLine()
它在我的电脑里运行没有任何问题。也许你可以在你的文章中加入更多的上下文。如果发生错误是什么等,我想知道是否需要显式的“文件关闭”;这就是myFile.Close,一旦您写入了额外的行。@Asocia运行时不会返回任何错误。它只是不在顶部追加空白行。在我的机器上运行,但是我必须把OpenOS.PATH.CouthFooFrPoT、文件、R+作为Myfile:放进去。是的,这一定是问题所在。我将folderPath设置为。因为我没有这样的目录,但是你需要给出完整的路径。
import os
folderPath = "./textFiles"
def myFilesAddEmptyLine():
for file in os.listdir(folderPath):
if file.endswith(".txt"):
with open(os.path.join(folderPath, file), "r+") as myFile: #This is the line that needed changing.
fileContent = myFile.read()
myFile.seek(0, 0)
myFile.write("\n" + fileContent)
print(myFile)
myFilesAddEmptyLine()