簡體   English   中英

Python - 從文件夾中更改 .txt 文件的內容並保存在新文件夾中

[英]Python - changing content of .txt files from folder and saving in new folder

我需要為此使用字典結構更改多個 .txt 文件中的一些關鍵詞。 然后,將更改的文件保存在新的本地化中。 我寫了下面附加的代碼,但是當我運行它時,它一直在運行,當我破壞它時,只有一個空文件創建。

import os
import os.path
from pathlib import Path

dir_path = Path("C:\\Users\\myuser\\Documents\\scripts_new")

#loading pair of words from txt file into dictionary

myfile = open("C:\\Users\\myuser\\Desktop\\Python\\dictionary.txt")
data_dict = {}
for line in myfile:
    k, v = line.strip().split(':')
    data_dict[k.strip()] = v.strip()
 
myfile.close()

# Get the list of all files and directories
path_dir = "C:\\Users\\myuser\\Documents\\scripts"


# iterate over files in
# that directory

for filename in os.listdir(path_dir):
    f = os.path.join(path_dir, filename)
    name = os.path.join(filename)
    text_file = open(f)

  #read whole file to a string
sample_string = text_file.read()

 # Iterate over all key-value pairs in dictionary

for key, value in data_dict.items():

    # Replace key character with value character in string
    
    sample_string = sample_string.replace(key, value)


with open(os.path.join(dir_path,name), "w") as file1:
    toFile = input(sample_string)
    file1.write(toFile)

嗯...我認為您的問題實際上可能是使用該行

toFile = input(sample_string)

因為這將停止等待用戶輸入的程序

無論如何,它可能與功能的小組織有關。 甚至下面的這個也有點……嗯。

import os
import os.path
from pathlib import Path

dir_path = Path("C:\\Users\\myuser\\Documents\\scripts_new")

# -----------------------------------------------------------
def load_file(fileIn):
    #loading pair of words from txt file into dictionary

    with open(fileIn) as myfile:
        data_dict = {}
        for line in myfile:
            k, v = line.strip().split(':')
            data_dict[k.strip()] = v.strip()

    return data_dict

# -----------------------------------------------------------
def work_all_files(starting_dir, moved_dir, data_dict):
   # Iterate over files within the dir - note non recursive
    for filename in os.listdir(starting_dir):
        f = os.path.join(starting_dir, filename)

        with open(f, 'r') as f1:
            #read whole file to a string
            sample_string = f1.read()

        new_string = replace_strings(sample_string, data_dict)

    with open(os.path.join(moved_dir, filename), "w") as file1:
        file1.write(new_string)

# -----------------------------------------------------------
def replace_strings(sample_string, data_dict):
    # Iterate over all key-value pairs in dictionary
    # and if they exist in sample_string, replace them

    for key, value in data_dict.items():
        # Replace key character with value character in string
        sample_string = sample_string.replace(key, value)

    return sample_string

# -----------------------------------------------------------
if __name__ == "__main__":
    # Get the dict-val pairings first
    data_dict = load_file("C:\\Users\\myuser\\Desktop\\Python\\dictionary.txt")

    #Then run over all the files within dir
    work_all_files("C:\\Users\\myuser\\Documents\\scripts", "C:\\Users\\myuser\\Documents\\new_scripts", data_dict)

我們可以將所有這些都放在一個類中,然后使用實例(即“self”)傳輸一些變量——這樣會更干凈。 但第一步是學習將事物分解為功能。

我找到了一個解決方案,方法有點不同。 也許這段代碼可能對某人有用:

import os

#loading pair of words from txt file into dictionary
myfile = open("C:\\Users\\user\\Desktop\\Python\\dictionary.txt")
data_dict = {}
for line in myfile:
    k, v = line.strip().split(':')
    data_dict[k.strip()] = v.strip()
 
myfile.close()

sourcepath = os.listdir("C:\\Users\\user\\Documents\\scripts\\")

for file in sourcepath:
        input_file =  "C:\\Users\\user\\Documents\\scripts\\" + file
        print('Conversion is ongoing for: ' + input_file)
        with open(input_file, 'r') as input_file:
            filedata = input_file.read()
        destination_path =  "C:\\Users\\user\\Documents\\scripts_new\\"+ file

         # Iterate over all key-value pairs in dictionary

        for key, value in data_dict.items():

            filedata = filedata.replace(key,value)

        with open(destination_path,'w') as file:
            file.write(filedata)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM