我有一个Python脚本,它将遍历Test Folder
(在这种情况下)中的所有目录,并将删除每个文件名的开头的所有数字。所以我的问题是如何修改我的脚本以从整个文件名中删除数字?不仅仅是它的开始或结束。
谢谢, 亚历
import os
for root, dirs, files in os.walk("Test Folder", topdown=True):
for name in files:
if (name.startswith("01") or name.startswith("02") or name.startswith("03") or name.startswith("04") or name.startswith("04") or name.startswith("05") or name.startswith("06") or name.startswith("07") or name.startswith("08") or name.startswith("09") or name[0].isdigit()):
old_filepath = (os.path.join(root, name))
_, new_filename = name.split(" ", maxsplit=1)
new_filepath = (os.path.join(root, new_filename))
os.rename(old_filepath, new_filepath)
答案 0 :(得分:5)
使用正则表达式,尤其是re.sub
:
>>> import re
>>> filename = '12name34with56numbers78in9it.txt'
>>> re.sub(r'\d', '', filename)
'namewithnumbersinit.txt'
这将取代与\d
模式匹配的所有内容,即带有''
的数字,即无效。
如果您想保护扩展程序,它会变得更加混乱。您必须从字符串中拆分扩展名,替换第一部分中的数字,然后重新加入扩展名。 os.path.splitext
可以帮助您:
>>> filename = '12name34with56numbers78in9it.mp3'
>>> name, ext = os.path.splitext(filename)
>>> re.sub(r'\d+', '', name) + ext
'namewithnumbersinit.mp3'
答案 1 :(得分:1)
你可以这样做:
class Program
{
static void Main(string[] args)
{
callCount();
}
static void count()
{
for (int i = 0; i < 5; i++)
{
System.Threading.Thread.Sleep(2000);
Console.WriteLine("count loop: " + i);
}
}
static async void callCount()
{
Task task = new Task(count);
task.Start();
for (int i = 0; i < 3; i++)
{
System.Threading.Thread.Sleep(4000);
Console.WriteLine("Writing from callCount loop: " + i);
}
Console.WriteLine("just before await");
await task;
Console.WriteLine("callCount completed");
}
}
无需进口。
答案 2 :(得分:0)
import os
def rename_files():
# Get files names from the directory
files_names = os.listdir(" file r directory path")
saved_dir = os.chdir(files_name)
# To get cutrrent working directiry name
print os.getcwd() # This is to verify whether you are in correct path
for file_name in files_names:
os.rename(file_name,file_name.translate(None,'0123456789'))
# Above translate function remove all the number from file name
rename_files()