gpt4 book ai didi

python - 如何将以下函数应用于多个txt文件?

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

您好,我的目录中有几个 txt 文件,我想将以下 python 函数应用于我的所有 txt 文件:

file = open('folder/testing.txt', 'r',encoding='utf-8') 
list_lines = []
for line in file:
list_lines.append(line.replace('-\n', ' '))
list_lines2 = []
for line in list_lines:
list_lines2.append(line.replace('-\n', ''))
list_lines3 = []
for line in list_lines2:
list_lines3.append(line.replace('\n', ''))
big_line = ''.join(list_lines3)
text_file=`open("folder/Output.txt", "w")`
print(big_line)
text_file.write(big_line)
text_file.close()
print('writing document')

为了实现这一目标,我尝试创建一个函数:

def change(document,encoding):
file = open(document, 'r',encoding=encoding)
list_lines = []
for line in file:
#print(line.replace('\n', ' ').replace('\r', ''))
list_lines.append(line.replace('-\n', ' '))
list_lines2 = []
for line in list_lines:
list_lines2.append(line.replace('-\n', ''))
list_lines3 = []
for line in list_lines2:
list_lines3.append(line.replace('\n', ''))
big_line = ''.join(list_lines3)
text_file = open(document+'changed', "w")
print(big_line)
text_file.write(big_line)
text_file.close()
print('writing document')

事实上,我的函数运行得很好,但是我有一个像这样的目录:

folder$ ls

file1.txt file2.txt file3.txt ... fileN.txt

因此,我希望感谢支持找到一种方法将我的函数应用于目录中所有以 txt 扩展名结尾的文档,感谢您的支持

最佳答案

使用 glob 将您的 change 函数应用于当前目录中以“.txt”结尾的每个文件非常容易:

import glob

for file in glob.glob("*.txt"):
change(file, "utf-8")

虽然这不是问题,但我无法在不建议这个较短版本的 change 的情况下查看此代码:

def change(document,encoding):
with open(document, 'r',encoding=encoding) as file:
list_lines = [line.replace('-\n', ' ').replace('\n', '') for line in file]
big_line = ''.join(list_lines)
print(big_line)
with open(document+'changed', "w") as text_file:
text_file.write(big_line)
print('writing document')

关于python - 如何将以下函数应用于多个txt文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48653204/

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