使用操作系统在python中修改文件。

2024-03-29 02:06:52 发布

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

我有一个父目录和子目录列表。每个子目录都包含一个名为数据.json. 我想遍历所有子目录,并在数据.json文件。我如何做到这一点?目前我正在做以下工作:

  for dir,dirs, files in os.walk("."):
        for filename in files:
            if file == 'data.json':
             with open(file, 'r') as f:
             #carry out editing operation

但我没有看到任何编辑发生。我怀疑数据.json找不到文件。你知道吗


Tags: 文件数据in目录json列表forif
1条回答
网友
1楼 · 发布于 2024-03-29 02:06:52

首先,您需要使用完整路径正确访问文件:

for path, subdirs, files in os.walk("."):
    for filename in files:
        if filename == 'data.json':
            fullpath = os.path.join(path, filename)

然后在所需的模式下打开它,其中包括read

with open(fullpath, 'r') as f:
    ...

阅读更多关于open()here模式的信息。你知道吗

相关问题 更多 >