Python 根据扩展名更改文件名

时间:2021-06-21 02:17:10

标签: python

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

我正在尝试根据以前的名称将 csv 文件重命名为 rawfile.csv ,它总是以部分开头,做一段时间,然后删除另一个文件,但不起作用。有没有办法根据扩展名重命名?

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 

2 个答案:

答案 0 :(得分: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)

注意:使用此代码时要小心,因为它会删除除以“part”开头并以“.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)

答案 1 :(得分:0)

认为您想使用 .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...