文件存在时文件名中的递增编号 [英] Incrementing number in file name when file exists

查看:209
本文介绍了文件存在时文件名中的递增编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Python(3)还是很陌生.我有大量的传感器数据,但是下载限制迫使我分块而不是一次检索所有数据(下载的每个.zip文件都包含给定时间段内每个传感器数据的.csv文件文件夹).因此,我有几十个大的.csv文件分布在几个文件夹中,我最终希望将每个传感器的全部数据合并/合并/附加到一个.csv文件中.为了使事情更复杂,每个传感器的.csv文件名在文件夹中相同.我开发了以下代码来将文件重命名并将其移动到一个文件夹中,以便以后可以合并/合并/追加.除了我要插入新文件名中的数字没有递增的事实外,它工作正常.

I am still very new to Python (3). I have a BUNCH of sensor data, but the download limit forces me to retrieve the data in chunks instead of all at once (each .zip file downloaded contains a folder of .csv files for each sensor's data during a given time period). Thus, I have dozens of large .csv files distributed among several folders that I would eventually like to concat/merge/append into one .csv file for each sensor's full data. To make things more complicated, .csv file names for each sensor are identical across the folders. I have developed the following code to rename and move the files into one folder so that later I can concat/merge/append. It works fine except for the fact that the number I am inserting into the new file name is not incrementing.

import os
path = r"C:\directory\sensordatafolders" #folders with .csv files
newPath = r"C:\directory\new" #destination for renamed files
for root, dirs, files in os.walk(path):
    for name in files:
        base, extension = os.path.splitest(name)
        if not os.path.exists(os.path.join(newPath, base + extension))
             oldfile = os.path.join(os.path.abspath(root), name)
             newfile = os.path.join(newPath, base + extension)
             os.rename(oldfile, newfile)
        else:
             i = 1
             oldfile = os.path.join(os.path.abspath(root), name)
             newfile = os.path.join(newPath, base + '_' + str(i) + extension)
             i +=1
             os.rename(oldfile, newfile)

第二个循环(* .csv和* _1.csv文件已成功移动)后,出现无法在该文件已经存在时创建文件"错误.这是因为(我认为)它一直在尝试创建* _1.csv文件,而不是增加到* _2.csv等.

After the second loop (*.csv and *_1.csv files successfully moved), it gives me the 'cannot create a file when that file already exists' error. This is because (I think) it keeps trying to create *_1.csv files instead of incrementing to *_2.csv, etc..

推荐答案

您的

i = 1 

在其他地方不应该出现的情况下,它将i设置为1,因此总是将i的值设置为2,并尝试将其放在for语句之外

After else should not be there, it keeps setting i to 1 thus always making i's value in to a 2, try to have it outside of the for statements

这篇关于文件存在时文件名中的递增编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆