亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在從一個文件夾到另一個 Python 的傳輸過程中修改多個文件

在從一個文件夾到另一個 Python 的傳輸過程中修改多個文件

慕神8447489 2022-12-06 14:53:53
現在我有一個程序可以將文件從 SOURCE 文件夾中的子目錄移動到 DESTINATION 文件夾中的子目錄。這些文件包含如下信息: 移動前的文件內容?,F在,在從 SOURCE 到 DESTINATION 的移動過程中,我想在 2 個地方修改移動文件。我想復制時間并將其粘貼為時間下的 TimeDif。類型保持為 Y,值必須是當前時間 - Time 的值。我想修改 Power * 10 的值。如果 Power 的值 =< 1000,則類型保持為 N,否則類型為 Power = Y因此,在文件從 SOURCE 移動到 DESTINATION 后,它必須如下所示:移動后的文件內容。這是我現在用于移動文件的代碼,所有移動工作都很順利。就是想修改文件內容的時候不知道從何下手:import os, os.pathimport time#Make source, destination and archive paths.source = r'c:\data\AS\Desktop\Source'destination = r'c:\data\AS\Desktop\Destination'archive = r'c:\data\AS\Desktop\Archive'#Make directory paths and make sure to consider only directories under source.for subdir in os.listdir(source):    subdir_path = os.path.join(source, subdir)    if not os.path.isdir(subdir_path):        continue#Now we want to get the absolute paths of the files inside those directories #and store them in a list.    all_file_paths = [os.path.join(subdir_path, file) for file in os.listdir(subdir_path)]    all_file_paths = [p for p in all_file_paths if os.path.isfile(p)]#Exclude empty sub-directories    if len(all_file_paths) == 0:        continue#Get only the newest files of those directories.    newest_file_paths = max(all_file_paths, key=os.path.getctime)#Now we are selecting the files which will be moved#and make a destination path for them.    for file_path in all_file_paths:        if file_path == newest_file_paths and os.path.getctime(newest_file_paths) < time.time() - 120:            dst_root = destination        else:            dst_root = archive#Now its time to make the move.        dst_path = os.path.join(dst_root, subdir, os.path.basename(file_path))        os.rename(file_path, dst_path
查看完整描述

3 回答

?
Qyouu

TA貢獻1786條經驗 獲得超11個贊

如果文件很小,那么您可以簡單地而不是移動文件:

  1. 從所有文件中讀取信息

  2. 找到要替換的數據

  3. 將新數據寫入源目錄中的文件

  4. 刪除舊文件

就像是

def move_file(file_path, dst_path):

  with open(file_path, "r") as input_file, open(dst_path, "w") as output_file:

      for line in input_file:

         if <line meets criteria to modify>:

             <modify_line>

         print(line, file=output_file)

      for <data> in <additional_data>:

         print(<data>, file=output_file)


  # remove the old file

  os.remove(file_path)

然后代替原始代碼中的 os.rename 調用 move_file 函數


#Now we are selecting the files which will be moved

#and make a destination path for them.

    for file_path in all_file_paths:

        if file_path == newest_file_paths and os.path.getctime(newest_file_paths) < time.time() - 120:

            dst_root = destination

        else:

            dst_root = archive

#Now its time to make the move.

        dst_path = os.path.join(dst_root, subdir, os.path.basename(file_path))

        move_file(file_path, dst_path)


你可以這樣實現


import os

import time

from datetime import datetime


SOURCE = r'c:\data\AS\Desktop\Source'

DESTINATION = r'c:\data\AS\Desktop\Destination'

ARCHIVE = r'c:\data\AS\Desktop\Archive'


def get_time_difference(date, time_string):

    """

    You may want to modify this logic to change the way the time difference is calculated.

    """

    time_difference = datetime.now() - datetime.strptime(f"{date} {time_string}", "%d-%m-%Y %H:%M")

    hours = time_difference.total_seconds() // 3600

    minutes = (time_difference.total_seconds() % 3600) // 60

    return f"{int(hours)}:{int(minutes)}"


def move_and_transform_file(file_path, dst_path, delimiter="\t"):

    """

    Reads the data from the old file, writes it into the new file and then 

    deletes the old file.

    """

    with open(file_path, "r") as input_file, open(dst_path, "w") as output_file:

        data = {

            "Date": None,

            "Time": None,

            "Power": None,

        }

        time_difference_seen = False

        for line in input_file:

            (line_id, item, line_type, value) = line.strip().split()

            if item in data:

                data[item] = value

                if not time_difference_seen and data["Date"] is not None and data["Time"] is not None:

                    time_difference = get_time_difference(data["Date"], data["Time"])

                    time_difference_seen = True

                    print(delimiter.join([line_id, "TimeDif", line_type, time_difference]), file=output_file)

                if item == "Power":

                    value = str(int(value) * 10)

            print(delimiter.join((line_id, item, line_type, value)), file=output_file)


    os.remove(file_path)


def process_files(all_file_paths, newest_file_path, subdir):

    """

    For each file, decide where to send it, then perform the transformation.

    """

    for file_path in all_file_paths:

        if file_path == newest_file_path and os.path.getctime(newest_file_path) < time.time() - 120:

            dst_root = DESTINATION

        else:

            dst_root = ARCHIVE


        dst_path = os.path.join(dst_root, subdir, os.path.basename(file_path))

        move_and_transform_file(file_path, dst_path)


def main():

    """

    Gather the files from the directories and then process them.

    """

    for subdir in os.listdir(SOURCE):

        subdir_path = os.path.join(SOURCE, subdir)

        if not os.path.isdir(subdir_path):

            continue


        all_file_paths = [

            os.path.join(subdir_path, p) 

            for p in os.listdir(subdir_path) 

            if os.path.isfile(os.path.join(subdir_path, p))

        ]


        if all_file_paths:

            newest_path = max(all_file_paths, key=os.path.getctime)

            process_files(all_file_paths, newest_path, subdir)


if __name__ == "__main__":

    main()


查看完整回答
反對 回復 2022-12-06
?
泛舟湖上清波郎朗

TA貢獻1818條經驗 獲得超3個贊

您的代碼肯定只是在修改文件而不是移動它們?我想移動和修改它們。順便說一句,如果我嘗試將您的代碼插入我的代碼,我會得到一個無效的語法。


import os

import time

from datetime import datetime


SOURCE = r'c:\data\AS\Desktop\Source'

DESTINATION = r'c:\data\AS\Desktop\Destination'

ARCHIVE = r'c:\data\AS\Desktop\Archive'


def get_time_difference(date, time_string):

    """

    You may want to modify this logic to change the way the time difference is calculated.

    """

    time_difference = datetime.now() - datetime.strptime(f"{date} {time_string}", "%d-%m-%Y %H:%M")

    hours = time_difference.total_seconds() // 3600

    minutes = (time_difference.total_seconds() % 3600) // 60

    return f"{int(hours)}:{int(minutes)}"


def move_and_transform_file(file_path, dst_path, delimiter="\t"):

    """

    Reads the data from the old file, writes it into the new file and then 

    deletes the old file.

    """

    with open(file_path, "r") as input_file, open(dst_path, "w") as output_file:

        data = {

            "Date": None,

            "Time": None,

            "Power": None,

        }

        time_difference_seen = False

        for line in input_file:

            (line_id, item, line_type, value) = line.strip().split()

            if item in data:

                data[item] = value

                if not time_difference_seen and data["Date"] is not None and data["Time"] is not None:

                    time_difference = get_time_difference(data["Date"], data["Time"])

                    time_difference_seen = True

                    print(delimiter.join([line_id, "TimeDif", line_type, time_difference]), file=output_file)

                if item == "Power":

                    value = str(int(value) * 10)

            print(delimiter.join((line_id, item, line_type, value)), file=output_file)


    os.remove(file_path)


def process_files(all_file_paths, newest_file_path, subdir):

    """

    For each file, decide where to send it, then perform the transformation.

    """

    for file_path in all_file_paths:

        if file_path == newest_file_path and os.path.getctime(newest_file_path) < time.time() - 120:

            dst_root = DESTINATION

        else:

            dst_root = ARCHIVE


        dst_path = os.path.join(dst_root, subdir, os.path.basename(file_path))

        move_and_transform_file(file_path, dst_path)


def main():

    """

    Gather the files from the directories and then process them.

    """

    for subdir in os.listdir(SOURCE):

        subdir_path = os.path.join(SOURCE, subdir)

        if not os.path.isdir(subdir_path):

            continue


        all_file_paths = [

            os.path.join(subdir_path, p) 

            for p in os.listdir(subdir_path) 

            if os.path.isfile(os.path.join(subdir_path, p))

        ]


        if all_file_paths:

            newest_path = max(all_file_paths, key=os.path.getctime)

            process_files(all_file_paths, newest_path, subdir)


if __name__ == "__main__":

    main()

查看完整回答
反對 回復 2022-12-06
?
慕斯709654

TA貢獻1840條經驗 獲得超5個贊

你不能修改移動它的方式。你首先必須移動它然后你才能做你的工作。為此,您可以將文件的最終目的地(包括名稱中的子目錄)存儲在一個數組中,稍后對其進行迭代以打開文件并完成您的工作。


這是一個最小的例子


def changeFile(fileName):

    # do your desired work here

    pass


files = ["dir/subdir1/file1", "dir/file"]


for file in files:

    os.rename(file, newPath)

    changeFile(newPath)


查看完整回答
反對 回復 2022-12-06
  • 3 回答
  • 0 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號