在Python中打开文件夹中的文件

2024-04-24 15:39:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我想打开一个要写入的文件。你知道吗

with open('test.txt','a') as textfile:
   ... 

它是这样工作的。你知道吗

现在我想从一个名为args.runkeyword. 你知道吗

with open(os.path.join(args.runkeyword, 'test.txt'),'a') as textfile:

t说找不到测试/测试.txt(假设runkeyword是test)。你知道吗

我还尝试了附加操作系统getcwd()但仍无法找到或创建文件。你知道吗

有什么想法吗?你知道吗


Tags: 文件pathtesttxtosaswithargs
2条回答
file = open('test.txt', 'a+')

你应该有'a+'而不是'a',+允许你附加。你知道吗

os.getcwd()实际上与你的工作无关。使用os.listdir()查看目录中的每个文件夹。如果任何东西被命名为test之前它可能是问题。你知道吗

像这样的递归函数可能对你有用

import os

def tara(directory):
    start = os.getcwd()
    files = []
    os.chdir(directory)

    for oge in os.listdir(os.curdir):
        if not os.path.isdir(oge):
            files.append(oge)
        else:
            files.extend(tara(oge))

    os.chdir(start)
    return files

相关问题 更多 >