这个问题之前遇到过,但是忘了怎么解决的了,现在记录一下,怕自己又忘了
目标:通过遍历文件夹,拼接一个返回文件的路径,然后修改原文件文件名:
import os
import pandas as pd
path = r'D:\test\ori_data'
for root,dir,files in os.walk(path):
for file in files:
# print(os.path.join(root,file))
pth = os.path.join(root,file)
filename = os.path.splitext(file)[0]
# print(type(filename))
re_path1 = os.path.join('re_',filename,'.txt')
print(re_path1)
但是得到的结果如下,感觉这条路不大合适,有斜杆,后面用replace试试
re_\id1\.txt
re_\id10\.txt
re_\id11\.txt
直接用replace就可以把id替换,但是这仅限于文件名十分有规律的情况下;
如果文件名没有规律,其实还是需要找别的办法来替代,这里或许是因为用os拼接的所以才会出现有斜杆的情况
import os
import pandas as pd
path = r'D:\test\ori_data'
for root,dir,files in os.walk(path):
for file in files:
# print(os.path.join(root,file))
pth = os.path.join(root,file)
filename = os.path.splitext(file)[0]
# print(type(filename))
# re_path1 = os.path.join('re_',filename,'.txt')
re_p = file.replace('id','re_id')
print(re_p)
如果文件名不规律的情况下,把filename先放进一个list,然后再进行拼接:
import os
import pandas as pd
path = r'D:\test\ori_data'
filenamelist = []
for root,dir,files in os.walk(path):
for file in files:
# print(os.path.join(root,file))
pth = os.path.join(root,file)
filename = os.path.splitext(file)[0]
filenamelist.append(filename)
# re_path1 = os.path.join('re_',filename,'.txt')
# print(filenamelist)
filepth1 = []
for i in filenamelist:
# 直接拼接要+r
a = r'D:\test\ori_data'+r'\re_'+i+'.txt'
print(a)
# os拼接更简单
# re_path = os.path.join(root,a)
filepth1.append(re_path)
print(re_path)
# print(filepth1)
D:\test\ori_data\re_id1.txt
D:\test\ori_data\re_id10.txt
D:\test\ori_data\re_id11.txt
D:\test\ori_data\re_id12.txt
突然想起来,换一个文件夹保存更简单了:
import os
import pandas as pd
path = r'D:\test\ori_data'
filenamelist = []
for root,dir,files in os.walk(path):
for file in files:
# print(os.path.join(root,file))
pth = os.path.join(root,file)
filename = os.path.splitext(file)[0]
filenamelist.append(filename)
此处得加转义的
re_path1 = os.path.join(r'D:\test\ori',filename)
print(re_path1)