gpt4 book ai didi

python - 如何用python在文件中写入列表

转载 作者:行者123 更新时间:2023-12-01 03:18:16 25 4
gpt4 key购买 nike

我的数据是这样组织的:我有 30 个文件夹。其中每个文件夹有 3 个子文件夹。其中每个文件都有一个文件。

我想编写一个脚本,在位于文件夹 1 的文本文件 1 中写入位于该文件夹 1 的子文件夹中的文件的路径;对于所有其他文件夹,依此类推。

问题是该脚本在每个文本文件中仅写入第三个文件(子文件夹 3 中的文件),而不是子文件夹 1、2、3 中的文件。

这是我尝试过的:

import glob
import os

gotofolders = '/path/to/folderslocation/'
foldersname = open('/path/to/foldersname.txt').read().split()

for folders in foldersname:
foldersdirectory = os.path.join(gotofolders,foldersname)
filepaths = glob.glob(os.path.join(foldersdirectory)+'*subfolders/*files')
for filepath in filepaths:
savethepaths = os.path.join(foldersdirectory)+'files_path_in_that_folder.txt'
with open (savethepaths,'w') as f:
f.write(filepath+'\n')

如上所述,它几乎可以工作,除了在每个“files_path_in_that_folder.txt”中我有“filepath”列表的第三个元素,而不是所有 3 个元素。

谢谢!

最佳答案

好吧,我明白了;我必须添加:

with open (savethepaths,'w') as f:
f.writelines(list("%s\n" %filepath for filepath in filepaths))

关于python - 如何用python在文件中写入列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42255619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com