从一个文件夹重写另一个文件夹中的文件并重命名它们

2024-06-07 22:18:27 发布

您现在位置:Python中文网/ 问答频道 /正文

一个简短的问题。我桌面上的tester文件夹中有多个文件。现在我想重写所有这些文件,在文件名末尾添加“moved”,并将它们移动到我桌面上名为tester1的新文件夹中。有人知道吗?先谢谢你。这是我当前的代码:

source = r'c:\data\AS\Desktop\tester'

#Take the absolute filepaths from all the files in tester and open them.
for file in os.listdir(source):
    file_paths = os.path.join(source, file)
    with open(file_paths, 'r') as rf:
        print(rf.read() + '\n')

Tags: 文件thein文件夹sourceos文件名open
2条回答

以下是您可以使用的:

import os
SourceFile="C:/Myfolder/Source/MyFile.txt"
TargetFile="C:/MyFolder/Target/MyFile_moved.txt"
os.rename(SourceFile,TargetFile)

希望有帮助

如果您的文件中有扩展名,并且希望在扩展名之前添加“moved”,则以下代码将起作用:

    import os
    import shutil

    src_path = "c:/data/AS/Desktop/tester/"
    dest_path = "c:/data/AS/Desktop/tester1/"

    for file in os.listdir(src_path):
        file_name, extension = file.split(".")
        shutil.move(src_path + file, dest_path + file_name + "moved." + extension)

如果文件中没有扩展名,则可以按如下方式更改代码:

    import os
    import shutil

    src_path = "c:/data/AS/Desktop/tester/"
    dest_path = "c:/data/AS/Desktop/tester1/"

    for file_name in os.listdir(src_path):
        shutil.move(src_path + file_name, dest_path + file_name + "moved")

我已经在MacOS中检查过了,如果您在Windows中遇到任何问题,请在评论中告诉我

相关问题 更多 >

    热门问题