How to rename a file using Python

2019-01-03 04:28发布

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

10条回答
神经病院院长
2楼-- · 2019-01-03 05:03

os.rename(old, new)

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

查看更多
We Are One
3楼-- · 2019-01-03 05:04

Use os.rename:

import os

os.rename('a.txt', 'b.kml')
查看更多
▲ chillily
4楼-- · 2019-01-03 05:08
    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)
查看更多
叛逆
5楼-- · 2019-01-03 05:09

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)
查看更多
倾城 Initia
6楼-- · 2019-01-03 05:10

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')
查看更多
一纸荒年 Trace。
7楼-- · 2019-01-03 05:10
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+

查看更多
登录 后发表回答