gpt4 book ai didi

python - 如何顺序查找文件并保存?

转载 作者:行者123 更新时间:2023-12-01 03:54:47 26 4
gpt4 key购买 nike

我有下面的代码,它首先尝试查找 PDF 文件。如果它甚至没有成功找到单个 PDF 文件,那么它会继续搜索,例如.TIF 文件位于同一文件夹中。

但是,我有两个问题。首先,当它在文件夹中找到 PDF 文件时,它还会打印 .txt 文件中的所有 .TIF 文件。但是,当它找不到 PDF 文件时,它就会停止(即使没有 break)并且不会生成 .txt 文件。我很困惑,感谢任何帮助。

b = os.walk('C:\\Users\\USER\\Desktop\\FOLDER')
os.listdir('C:\\Users\\USER\\Desktop\\FOLDER')
f = []
for(dirpath, dirnames, filenames) in b:
if f.extend(os.path.splitext(name)[0] for name in filenames if name.lower().endswith((".pdf"))) == []:
pass
break
elif f.extend(os.path.splitext(name)[0] for name in filenames if name.lower().endswith((".tif"))) == []:
pass


def save_to_file(text):
for name in f:
with open('C:\\Users\\USER\\Desktop\\FOLDER\\test.txt', mode='wt', encoding='utf-8') as myfile:
myfile.write('\n'.join(text))
myfile.write('\n')

save_to_file(f)

最佳答案

试试这个:

import os

def gather_files(folder, ending):
contents = os.walk(folder)
files = []
for (dirpath, dirnames, filenames) in contents:
files += ([file.splitext()[0] for file in filenames if file.lower().endswith(ending)])
return files


def main():
f = gather_files("test", ".pdf")
if not f:
f = gather_files("test", ".tif")

if not f:
print("No .pdf or .tif files found in the given directory.")
else:
with open("test_out.txt", "w", encoding="utf-8") as output:
output.write("\n".join(f) + "\n")

if __name__ == "__main__":
main()

这应该适合你。作为替代方案,您可以通过硬编码值(例如文件夹和结尾)将主要部分移动到方法 Gather_files,或者您可以在方法中提供关键字“alternative_ending”或类似的内容。

也许还要再看看你的代码。您有一个方法save_to_file(text),您用 f 调用它,并在其中迭代 f。可能是一个拼写错误,您应该迭代 text,而不是 f。但您根本不需要迭代,因为 text (或 f)包含作为字符串列表的文件名。所以

with open("test_out.txt", "w", encoding="utf-8") as output:
output.write("\n".join(text) + "\n")

会做你想做的一切。

关于python - 如何顺序查找文件并保存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37657781/

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