Python基于外部更改文件名



我有一个目录,spark将我的数据帧保存在csv中,但它也保存+3个文件扩展名crc。我需要将csv上传到我的blob,为此,我需要文件的名称,但spark总是用随机名称保存(总是以"part"开头(part0015154102102.csv。

我正试图根据以前的名称将csv文件重命名为rawfile.csv,该名称总是以part开头,做了一段时间,然后删除了另一个文件,但不起作用。有没有一种方法可以根据扩展名进行重命名?

path = """c:\Users\Cliente\Desktop\Notebooks\"""
novo_nome = 'rawfile.csv'
cont = 1
while (cont < 4):
for nome in os.listdir(dir):  
if file[:4] == 'part':
os.rename(path+"\"+nome, path+"\"+novo_nome)
else:
os.remove(file)                 
cont = cont + 1 

您可以使用nome.startswith('part') and nome.endswith('.csv')查找文件
如果我理解正确,下面的代码应该可以执行您想要的操作。

此外,您不需要while循环,因为for已经遍历了目录中的所有文件。

import os
path = "C:\Users\Cliente\Desktop\Notebooks\"
novo_nome = 'rawfile.csv'
cont = 1
for nome in os.listdir(path):
# if name is what we want, change it to novo_nome
if nome.startswith('part') and nome.endswith('.csv'):
os.rename(path + nome, path + novo_nome)

# else remove all the other files
else:
os.remove(path + nome)

注意:小心使用此代码,因为它将删除除以"开头的文件以外的所有内容;部分";并以"结尾;。csv">

您可以添加更多的检查以防止它删除自己(以防您将脚本放在同一文件夹中(,并在再次运行时防止它删除rawfile.csv

import os
path = "C:\Users\Cliente\Desktop\Notebooks\"
novo_nome = 'rawfile.csv'
cont = 1
for nome in os.listdir(path):
# if name is what we want, change it to novo_nome
if nome.startswith('part') and nome.endswith('.csv'):
os.rename(path + nome, path + novo_nome)
# else remove all the other files
# except if they are a .py or a .csv
elif not nome.endswith('.csv') and not nome.endswith('.py'):
os.remove(path + nome)

如果您想使用.splitext(),则测试扩展
https://docs.python.org/3/library/os.path.html

filename, extension = os.path.splitext( nome )
if extension = '.csv':
number = filename[4:]
print( number )
do stuff...

最新更新