如何使用Python重命名文件

问题:如何使用Python重命名文件

我想更改a.txtb.kml

I want to change a.txt to b.kml.


回答 0

用途os.rename

import os

os.rename('a.txt', 'b.kml')

Use os.rename:

import os

os.rename('a.txt', 'b.kml')

回答 1

文件可能位于目录中,在这种情况下,请指定路径:

import os
old_file = os.path.join("directory", "a.txt")
new_file = os.path.join("directory", "b.kml")
os.rename(old_file, new_file)

File may be inside a directory, in that case specify the path:

import os
old_file = os.path.join("directory", "a.txt")
new_file = os.path.join("directory", "b.kml")
os.rename(old_file, new_file)

回答 2

import shutil

shutil.move('a.txt', 'b.kml')

这将可以重命名或移动文件。

import shutil

shutil.move('a.txt', 'b.kml')

This will work to rename or move a file.


回答 3

从Python 3.4开始,可以使用pathlib模块解决此问题。

如果您使用的是旧版本,则可以使用此处找到的反向移植版本

假设您不在要重命名的根路径(只是给它增加了一点难度),而不必提供完整路径,我们可以看一下:

some_path = 'a/b/c/the_file.extension'

因此,您可以按照自己的路径创建一个Path对象:

from pathlib import Path
p = Path(some_path)

只是为了提供有关我们现在拥有的该对象的一些信息,我们可以从中提取内容。例如,如果出于某种原因,我们希望通过修改从文件名的文件重命名the_filethe_file_1,那么我们可以得到的文件名部分:

name_without_extension = p.stem

并仍将扩展名放在手边:

ext = p.suffix

我们可以通过简单的字符串操作来执行修改:

Python 3.6及更高版本使用f字符串!

new_file_name = f"{name_without_extension}_1"

除此以外:

new_file_name = "{}_{}".format(name_without_extension, 1)

现在,我们可以通过rename在创建的路径对象上调用方法并附加ext来完成所需的正确的重命名结构,从而执行重命名:

p.rename(Path(p.parent, new_file_name + ext))

更简短地展示其简单性:

Python 3.6及更高版本:

from pathlib import Path
p = Path(some_path)
p.rename(Path(p.parent, f"{p.stem}_1_{p.suffix}"))

低于Python 3.6的版本改用字符串格式方法:

from pathlib import Path
p = Path(some_path)
p.rename(Path(p.parent, "{}_{}_{}".format(p.stem, 1, p.suffix))

As of Python 3.4 one can use the pathlib module to solve this.

If you happen to be on an older version, you can use the backported version found here

Let’s assume you are not in the root path (just to add a bit of difficulty to it) you want to rename, and have to provide a full path, we can look at this:

some_path = 'a/b/c/the_file.extension'

So, you can take your path and create a Path object out of it:

from pathlib import Path
p = Path(some_path)

Just to provide some information around this object we have now, we can extract things out of it. For example, if for whatever reason we want to rename the file by modifying the filename from the_file to the_file_1, then we can get the filename part:

name_without_extension = p.stem

And still hold the extension in hand as well:

ext = p.suffix

We can perform our modification with a simple string manipulation:

Python 3.6 and greater make use of f-strings!

new_file_name = f"{name_without_extension}_1"

Otherwise:

new_file_name = "{}_{}".format(name_without_extension, 1)

And now we can perform our rename by calling the rename method on the path object we created and appending the ext to complete the proper rename structure we want:

p.rename(Path(p.parent, new_file_name + ext))

More shortly to showcase its simplicity:

Python 3.6+:

from pathlib import Path
p = Path(some_path)
p.rename(Path(p.parent, f"{p.stem}_1_{p.suffix}"))

Versions less than Python 3.6 use the string format method instead:

from pathlib import Path
p = Path(some_path)
p.rename(Path(p.parent, "{}_{}_{}".format(p.stem, 1, p.suffix))

回答 4

os.rename(old, new)

可以在Python文档中找到:http : //docs.python.org/library/os.html

os.rename(old, new)

This is found in the Python docs: http://docs.python.org/library/os.html


回答 5

使用os.rename。但是您必须将两个文件的完整路径传递给函数。如果a.txt我的桌面上有文件,则可以这样做,而且我也必须提供完整的重命名文件。

 os.rename('C:\\Users\\Desktop\\a.txt', 'C:\\Users\\Desktop\\b.kml')

Use os.rename. But you have to pass full path of both files to the function. If I have a file a.txt on my desktop so I will do and also I have to give full of renamed file too.

 os.rename('C:\\Users\\Desktop\\a.txt', 'C:\\Users\\Desktop\\b.kml')

回答 6

import os

# Set the path
path = 'a\\b\\c'  
# save current working directory
saved_cwd = os.getcwd()
# change your cwd to the directory which contains files
os.chdir(path)
os.rename('a.txt', 'b.klm')
# moving back to the directory you were in 
os.chdir(saved_cwd)
import os

# Set the path
path = 'a\\b\\c'  
# save current working directory
saved_cwd = os.getcwd()
# change your cwd to the directory which contains files
os.chdir(path)
os.rename('a.txt', 'b.klm')
# moving back to the directory you were in 
os.chdir(saved_cwd)

回答 7

您可以使用os.system调用终端来完成任务:

os.system('mv oldfile newfile')

You can use os.system to invoke terminal to accomplish the task:

os.system('mv oldfile newfile')

回答 8

import os
import re
from pathlib import Path

for f in os.listdir(training_data_dir2):
  for file in os.listdir( training_data_dir2 + '/' + f):
    oldfile= Path(training_data_dir2 + '/' + f + '/' + file)
    newfile = Path(training_data_dir2 + '/' + f + '/' + file[49:])
    p=oldfile
    p.rename(newfile)
import os
import re
from pathlib import Path

for f in os.listdir(training_data_dir2):
  for file in os.listdir( training_data_dir2 + '/' + f):
    oldfile= Path(training_data_dir2 + '/' + f + '/' + file)
    newfile = Path(training_data_dir2 + '/' + f + '/' + file[49:])
    p=oldfile
    p.rename(newfile)

回答 9

import shutil
import os

files = os.listdir("./pics/") 

for key in range(0, len(files)):
   print files[key]
   shutil.move("./pics/" + files[key],"./pics/img" + str(key) + ".jpeg")

这应该做。python 3+

import shutil
import os

files = os.listdir("./pics/") 

for key in range(0, len(files)):
   print files[key]
   shutil.move("./pics/" + files[key],"./pics/img" + str(key) + ".jpeg")

This should do it. python 3+