[英]remove characters from every file name in directory with python
So I am writing a piece of code that needs to iterate through hundreds of files in a directory.所以我正在编写一段代码,它需要遍历目录中的数百个文件。 With every filt it needs to filter out certain pieces of information in it then put it in a new file with a modified name.
每次过滤时,它都需要过滤掉其中的某些信息,然后将其放入具有修改名称的新文件中。
For example, a file called 1100006_0.vcf
or 5100164_12.vcf
must have a file created called 1100006.vcf
and 5100164.vcf
respectively.例如,名为
1100006_0.vcf
或5100164_12.vcf
的文件必须创建一个分别名为1100006.vcf
和5100164.vcf
的文件。 Can you point me in the right direction for this?你能指出我正确的方向吗?
EDIT: To make code Generic and rename file names from one directory to any other directory/folder try following.编辑:要使代码通用并将文件名从一个目录重命名为任何其他目录/文件夹,请尝试以下操作。 I have kept this program inside
/tmp
and renamed the files inside /tmp/test
and it worked fine(in a Linux system).我将这个程序保存在
/tmp
中,并重命名了/tmp/test
中的文件,它运行良好(在 Linux 系统中)。
#!/usr/bin/python3
import os
DIRNAME="/tmp/test"
files = os.listdir(DIRNAME)
for f in files:
if '.vcf' in f:
newname = f.split('_')[0]
newname = newname + '.vcf'
os.rename(os.path.join(DIRNAME,f), os.path.join(DIRNAME,newname))
Since you want to rename the files, so we could use os
here.由于您要重命名文件,因此我们可以在此处使用
os
。 Written and tested with shown samples in python3, I have given DIRNAME
as /tmp
you could give your directory where you want to look for files.在 python3 中使用显示的示例编写和测试,我将
DIRNAME
指定为/tmp
,您可以将目录提供给您要查找文件的位置。
#!/usr/bin/python3
import os
DIRNAME="/tmp"
files = os.listdir(DIRNAME)
for f in files:
if '.vcf' in f:
newname = f.split('_')[0]
newname = newname + '.vcf'
os.rename(f, newname)
As posted by RavinderSingh13, the code was fine, the only issue was that in renaming them, I would have two files of the same name (the difference between them was the underscore and number that I needed removed).正如 RavinderSingh13 所发布的,代码很好,唯一的问题是在重命名它们时,我会有两个同名的文件(它们之间的区别是我需要删除的下划线和数字)。
#!/usr/bin/python3
import os
DIRNAME="/tmp"
files = os.listdir(DIRNAME)
for f in files:
if '.vcf' in f:
newname = f.split('_')[0]
newname = newname + '.vcf'
os.rename(f, newname)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.