gpt4 book ai didi

Python 3.6 : Looping through files in os. listdir() 并将其中一些写入文本文档

转载 作者:太空宇宙 更新时间:2023-11-03 14:40:30 24 4
gpt4 key购买 nike

我正在尝试循环访问一些文件并将 .txt 文件的文件名写入另一个 .txt

这段代码在找到并写入一个文件的名称后停止。

我怎样才能让它写出其余人的名字?

import os

os.chdir('/users/user/desktop/directory/sub_directory')

for f in os.listdir():
file_name, file_ext = os.path.splitext(f)
if file_ext == '.txt':
with open('file_test.txt', 'r+') as ft:
ft.write(file_name)

最佳答案

您需要以“追加”模式打开目标文件

import os

os.chdir('/users/user/desktop/directory/sub_directory')

for f in os.listdir():
file_name, file_ext = os.path.splitext(f)
if file_ext == '.txt':
with open('file_test.txt', 'a+') as ft:
ft.write(file_name)

只需将“a+”作为打开函数的第二个参数(其中“a”代表“追加”,“+”代表“如果不存在则创建”)。我建议您在写入函数中添加分隔符(如“\n”)以获得更具可读性的结果

关于Python 3.6 : Looping through files in os. listdir() 并将其中一些写入文本文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46583512/

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