将重命名的文本文件保留在原始文件夹中

时间:2016-11-07 16:48:49

标签: python python-3.x

这是我目前(来自Jupyter笔记本)的代码,用于重命名某些文本文件。 问题是当我运行代码时,重命名的文件放在我当前工作的Jupyter文件夹中。我希望文件保留在原始文件夹中

import glob
import os

path = 'C:\data_research\text_test\*.txt'

files = glob.glob(r'C:\data_research\text_test\*.txt')

for file in files:           
     os.rename(file, file[-27:])

2 个答案:

答案 0 :(得分:1)

您应该只更改名称并保持路径相同。您的文件名不会总是超过27,因此将其放入代码中并不理想。你想要的只是将名称与路径分开,无论名称如何,无论路径如何。类似的东西:

import os
import glob

path = 'C:\data_research\text_test\*.txt'

files = glob.glob(r'C:\data_research\text_test\*.txt')

for file in files:    
    old_name = os.path.basename(file)  # now this is just the name of your file
    # now you can do something with the name... here i'll just add new_ to it.
    new_name = 'new_' + old_name # or do something else with it
    new_file = os.path.join(os.path.dirname(file), new_name)  # now we put the path and the name together again
    os.rename(file, new_file)  # and now we rename.

如果您使用的是Windows,则可能需要使用ntpath包。

答案 1 :(得分:0)

file[-27:]获取文件名的最后27个字符,因此除非您的所有文件名长度为27个字符,否则它将失败。如果成功,则删除目标目录名称,以便将文件移动到当前目录。 os.path具有管理文件名的实用程序,您应该使用它们:

import glob
import os

path = 'C:\data_research\text_test*.txt'

files = glob.glob(r'C:\data_research\text_test*.txt')

for file in files:
    dirname, basename = os.path.split(file)
    # I don't know how you want to rename so I made something up
    newname = basename + '.bak'
    os.rename(file, os.path.join(dirname, newname))