我有一个目录,其中 spark 将我的数据帧保存在 csv 中,但它也保存了 + 3 个文件扩展名 crc。我需要将 csv 上传到我的 blob,为此,我需要文件的名称,但 spark 总是使用随机名称(始终以“part”开头) part0015154102102.csv 进行保存。
我正在尝试将 csv 文件重命名为 rawfile.csv ,基于以前的 name ,它总是以 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)
您可以添加更多检查以防止它自行删除(以防您将脚本放在同一文件夹中)并防止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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句