将一个文件夹中的文件重写到另一个文件夹,并重命名它们。
将一个文件夹中的文件重写到另一个文件夹,并重命名它们。
此问题已有答案:
一个简短的问题。我在桌面上有一个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')
admin 更改状态以发布 2023年5月23日
如果您的文件具有扩展名,并且想在扩展名前添加“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上遇到任何问题,请在评论中告诉我。