繁体   English   中英

处理多个文本文件

[英]Manipulating multiple text files

我试图遍历一些文件,一个一个打开它们,操作其中的文本,关闭并重命名文件。

代码

import os
path = "C:\Converter"
os.chdir(path)

def read_text_file(file_path):
    with open(file_path, 'r') as f:
        print(f.read())

for file in os.listdir():
    if file.endswith(".txt"):
        file_path = f"{path}\{file}"
        read_text_file(file_path)

with open(file_path, 'r') as file:
     search_text='@'
     replace_text='~'
     data = file.read()
     data = data.replace(search_text, replace_text)
     data = data.replace('\n', '')
  
with open(file_path, 'w') as file:
        file.write(data)

print("File Modified!")

os.rename(file_path, file_path + "_Fixed.txt")

问题

但我想不通。 我对 Python 很陌生。

这是您的代码示例,其中缺少计算部分,请查看它并让我知道这是否是您所需要的。 此外,我还建议您开始在代码中使用注释,例如,如果您尝试这样做,请键入一小部分代码并确定它是否是您想要的,然后这样命名。

# Import required libraries
import os
# Nice path
path = "C:\Converter"
os.chdir(path)
# Totally not required but lets keep your style ;)
def read_text_file(file_path):
    with open(file_path, 'r') as f:
        print(f.read())
# Open all files ending with .txt in the current directory
for file in os.listdir():
    if file.endswith(".txt"):
        file_path = f"{path}\{file}"
        file_to_be_fixed = read_text_file(file_path)
        # Now we're adding here the logic to fix our file        
        with open(file_to_be_fixed, 'r') as file_to_fix:
            search_text='@'
            replace_text='~'
            data = file_to_fix.read()
            data = data.replace(search_text, replace_text)
            data = data.replace('\n', '')
            # now we're writing the fixed file
            with open(file_path, 'w') as file:
                file.write(data)
                os.rename(file_path, file_path + "_Fixed.txt")
                print("File Modified and saved as " + file_path + "_Fixed.txt")

假设您要做的就是在您指定的目录中找到所有 txt 文件并将“@”替换为“~”并删除所有新行。 您的问题似乎是修改、写入和重命名文件的代码块不在读取文件名的 for 循环内。 这只是向代码块添加正确缩进的问题。 我能够如下所示修改您的代码,它在 Windows 上使用 Python 3.11.0 按预期工作。

import os
path = "C:\Converter"
os.chdir(path)

def read_text_file(file_path):
    with open(file_path, 'r') as f:
        print(f.read())

for file in os.listdir():
    if file.endswith(".txt"):
        file_path = f"{path}\{file}"
        read_text_file(file_path)

        with open(file_path, 'r') as file:
            search_text='@'
            replace_text='~'
            data = file.read()
            data = data.replace(search_text, replace_text)
            data = data.replace('\n', '')
          
        with open(file_path, 'w') as file:
                file.write(data)

        print("File Modified!")

        os.rename(file_path, file_path + "_Fixed.txt")

如果您还有其他问题或不理解,请发表评论。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM