简体   繁体   English

更改文件夹中的文件名

[英]Changing filenames in folders

I have a folder that contains a lot of files that has a lot of copies which make them unreadable.我有一个文件夹,其中包含很多文件,这些文件有很多副本,使它们不可读。

Example:例子:

cow.txt
cow.txt(1)
cow.txt(2)
cow.txt(3)
dog.txt
dog.txt(1)

I would like to to have all the files structured in away that makes them able to be opened.我希望将所有文件结构化,使它们能够打开。 Example例子

cow.txt
cow(1).txt
cow(2).txt
cow(3).txt
dog.txt
dog(1).txt

Any help you can provided would be greatly appreciated.您可以提供的任何帮助将不胜感激。 I am just looking to make sure there name is changed, and am not looking to read each individual file.我只是想确保名称已更改,而不是要读取每个单独的文件。 In addition if possible I would like to break up the files into 20k blocks.此外,如果可能的话,我想将文件分成 20k 块。 Thank you in advance.先感谢您。

I have tried using os.rename to simply rename the file but I am confused on how to do the efficiently as the numbers come after the.txt I then decided to read all the files and convert them to a pandas data frame and fix it that way.我曾尝试使用 os.rename 来简单地重命名文件,但我对如何有效地进行操作感到困惑,因为数字位于 .txt 之后,然后我决定读取所有文件并将它们转换为 pandas 数据框并修复它方法。 However I am confused on how to pull the files and make them with that name.但是,我对如何提取文件并使用该名称制作它们感到困惑。

list_of_files = os.listdir()
df = pd.DataFrame(list_of_files, columns  = ['File_Name'])
df['.txt_removed'] = df.replace(to_replace = '.txt', value = '', regex = True)
df['txt_add'] = df['.txt_removed'] + '.txt'

To pull the files I would do something like this要提取文件,我会做这样的事情

for filewant_in df['txt_add']:
     if filewant in os.listdir():
         sutil.copy(os.path.join(filewant), 'new location')

I do not think this option will work even though it gives me my intended result.我不认为这个选项会起作用,即使它给了我预期的结果。 As I would like to change the overall file names.因为我想更改整体文件名。

You can use python's standard library, the os module has the os.rename function.你可以使用python的标准库, os模块有os.rename function。

Like this:像这样:

It works like this:它是这样工作的:

os.rename('cow.txt(1)', 'cow(1).txt')

Create a.py file and paste the code below then run it.创建一个 .py 文件并粘贴下面的代码,然后运行它。 Change /mydir path with the path to the directory having the files.将 /mydir 路径更改为包含文件的目录的路径。 The code will loop through the directory finding all the containing have.txt as part of the file extension and renaming them to a.txt file.代码将在目录中循环查找所有包含 have.txt 作为文件扩展名的一部分,并将它们重命名为 a.txt 文件。 I hope it works.我希望它有效。

import glob, os
os.chdir("/mydir")
for file in glob.glob("*.txt*"):
    file_name = os.path.basename(file)
    part_name = file_name.split(".", 1)
    new_name = part_name[0]+'.txt'
    os.rename(file,new_name) 

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

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