简体   繁体   English

如何使用python重命名目录中的文件

[英]how to rename file in a directory using python

I have a file named "x.mkv" in a folder named "export". 我在名为“ export”的文件夹中有一个名为“ x.mkv”的文件。 X could be anything.. it's not named exactly X, it's just file with some name. X可以是任何东西..它的名称不完全是X,它只是带有某些名称的文件。 I want to rename the file to "Movie1 x [720p].mkv". 我想将文件重命名为“ Movie1 x [720p] .mkv”。 I want to keep the file's original name and add Movie1 as prefix and [720p] as a suffix. 我想保留文件的原始名称,并添加Movie1作为前缀,并添加[720p]作为后缀。 There is just one file in the folder, nothing more. 文件夹中只有一个文件,仅此而已。 How do I do so? 我该怎么做? I tried using variables in os.rename and i failed.. this is what I used : 我尝试在os.rename中使用变量,但失败了。

import os
w = os.listdir("C:/Users/UserName/Desktop/New_folder/export")
s = '[Movie1]' + w + '[720p]'
os.rename(w,s)

What I'm trying to do is... get the file name from the folder, as there is and will be only 1 file, so, this seems appropriate. 我想做的是...从文件夹中获取文件名,因为这里只有一个文件,因此,这似乎很合适。 saving the fetch results in 'w' and then using another variable 's' and adding prefix and suffix. 将提取结果保存为“ w”,然后使用另一个变量“ s”并添加前缀和后缀。 Then at the end, I fail at using the variables in ' os.rename ' command. 然后最后,我无法在' os.rename '命令中使用变量。

Your original won't work for a few reasons: 您的原件由于以下几个原因而无法使用:

  1. os.listdir() returns a list and not a string so your string concatenation will fail. os.listdir()返回一个列表,而不是一个字符串,因此您的字符串连接将失败。
  2. os.rename() will have trouble renaming the file unless the path is given or you change the cwd. 除非给出路径或更改cwd,否则os.rename()将无法重命名文件。

I'd suggest the following code: 我建议以下代码:

import os
path="C:/Users/UserName/Desktop/New_folder/export/"
w = os.listdir(path)
#since there is only one file in directory it will be first in list
#split the filename to separate the ext from the rest of the filename
splitfilename=w[0].split('.')
s = '[Movie1]' + '.'.join(splitfilename[:-1]) + '[720p].'+splitfilename[-1]
os.rename(path+w[0],path+s)

Use os.rename : 使用os.rename

def my_rename(path, name, extension, prefix, suffix):
    os.rename(path + '/' +          old_name          + '.' + extension,
              path + '/' + prefix + old_name + suffix + '.' + extension)

my_rename('/something/export', 'x', 'mkv', 'Movie1 ', ' [720p]')

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

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