Python 根据扩展名更改文件名

里卡多·考杜罗

我有一个目录,其中 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)

注意:请注意此代码,因为它会删除以“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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Python:如何将文件名更改为小写而不是扩展名

在Python中从文件名提取扩展名

在Python中获取不带扩展名的文件名

python对扩展名/文件名排序

在Python中更改文件扩展名

Python:检查扩展名列表中是否存在以扩展名结尾的文件名

从目录中提取文件名并在excel中根据其扩展名进行分类| 使用 Python

如何从Python中文件名列表中的文件名中删除扩展名?

文件扩展名Python

如何使用 python 的文件扩展名对目录中的文件名进行分组?

Python正则表达式匹配整个文件名包括文件扩展名

Python - 更改为不同的文件扩展名

Python中是否可以保证模块文件名中扩展名的导入顺序?

如何从Python路径中获取不带扩展名的文件名?

如何从 Python 中的路径获取不带扩展名的文件名?

如何在Python中从文件名替换(或剥离)扩展名?

如何从没有扩展名的路径中获取特定文件名python

FFmpeg输出相同的文件名,但不带python扩展名

python根据列表更改所有文件名

将具有不同扩展名的最旧文件名移动到公共文件夹。Python

Python 3-Tkinter-askopenfilename-通过正则表达式过滤文件名(不按扩展名)

如何在Python中选择文件名的一部分(保留扩展名)?

如何使用 Python 更改文件夹中的特定文件扩展名?

Python覆盖文件并更改文件名

Python-哪个命令更适合更改文件扩展名?

Python中文件类型检查器的文件扩展名

Python - 读取目录中的文件名,向文本文件写入两次(一次没有文件扩展名),并用管道分隔

Python 程序,用于生成文件名、扩展名、路径、创建时间和大小的字典,并将它们输出到 json 文件

如何在Python中通过扩展名删除文件?