Python根据文件中选定的字符复制和重命名许多小型csv文件
我不是程序员;我是一名飞行员,在过去的生活中只做过一点脚本编写,所以我对这方面完全不熟悉。我搜索了论坛,发现了一些类似的问题,如果有更多的专业知识和时间,我可能能够适应我的问题,但我希望我可以通过问自己的问题来接近这些问题。我希望我的问题足够独特,考虑到我的缺点,那些考虑回答的人不会觉得他们的时间被浪费了。无论如何,我的问题是: 我的一些工作人员定期需要根据应用于其内容的特定约定重命名几百到1000多个小型csv文件。并非所有的文件都在给定的项目中使用,但它们的任何子集都可以使用,因此自动化在这里非常有意义。目前,这是根据需要手动完成的。我可以轻松地将所有这些文件移动到一个目录中进行处理,因为它们的所有文件名在接收时都是唯一的 下面是两个示例csv文件的代表性摘录,前面是它们各自的文件名(我收到它们时):Python根据文件中选定的字符复制和重命名许多小型csv文件,python,csv,Python,Csv,我不是程序员;我是一名飞行员,在过去的生活中只做过一点脚本编写,所以我对这方面完全不熟悉。我搜索了论坛,发现了一些类似的问题,如果有更多的专业知识和时间,我可能能够适应我的问题,但我希望我可以通过问自己的问题来接近这些问题。我希望我的问题足够独特,考虑到我的缺点,那些考虑回答的人不会觉得他们的时间被浪费了。无论如何,我的问题是: 我的一些工作人员定期需要根据应用于其内容的特定约定重命名几百到1000多个小型csv文件。并非所有的文件都在给定的项目中使用,但它们的任何子集都可以使用,因此自动化在这
A_13LSAT_2014-04-23_1431.csv:
1,KDAL CURLO RW13L SAT 20140414_0644,SID,N/A,DDI
2,*,RW13L(AER),SAT
3,RW13L(AER),+325123.36,-0965121.20,RW31R(DER),+325031.35,-0965020.95
4,1,1.2,+325123.36,-0965121.20,0.0,+325031.35,-0965020.95,2.0
3,RW31R(DER),+325031.35,-0965020.95,GH13L,+324947.23,-0964929.84
4,1,2.4,+325031.35,-0965020.95,0.0,+324947.23,-0964929.84,2.0
5,TTT,0,0
5,CVE,0,0
A____2014-04-03_1419.csv:
1,KDFW SEEVR STAR RRONY SEEVR 20140403_1340,STAR,N/A,DDI
2,*,RRONY,SEEVR
3,RRONY,+333455.16,-0952530.56,ROWZE,+333233.02,-0954016.52
4,1,12.6,+333455.16,-0952530.56,0.0,+333233.02,-0954016.52,2.0
5,EIC,0,1
5,SLR,0,0
我知道这些文件不是代码,但我在这篇文章中输入了缩进,以便正确显示 由于使用这些文件的平台的8.3限制,必须重命名这些文件。 公约是: •在第一行,第二个“单元格”第二个字的前两个字符(第二个单元格的第6和第7个字符),以及 •第2行,第三个单元格的前三个字符,以及 •第四个单元格的前三个字符 文件的内容和格式必须保持不变。理论上,此约定为每个文件生成唯一的名称,因此文件名的重复不应该是一个问题 上述文件将分别复制和重命名为: CURW1SAT.csv SERROSEE.csv 就这样。这只是一个脚本,它将扫描一个包含这些csv文件的目录,并根据我刚才描述的约定,基于它们的内容在同一目录中创建重命名副本。我正在尝试使用Activestate Python 2.7.7
提前谢谢你的考虑。这不是你所说的漂亮,但我也不是;而且很有效(而且很简单)
只需将其放入包含所有要重命名的csv的文件夹中并运行它将其放入脚本中,运行它时,在命令行上为其指定目录名作为参数:
import csv
import sys
import os
def rename_csv_file(filename):
global directory
with open(filename,'r') as csv_file:
newfilename = str()
rownum = 0
filereader = csv.reader(csv_file,delimiter=',')
for row in filereader:
if rownum == 0:
newfilename = row[1].split()[1][:2]
elif rownum == 1:
newfilename += row[2][:3]
newfilename += row[3][:3]
break
rownum += 1
newfilename += '.csv'
newfullpath = os.path.join(directory,newfilename)
os.rename(filename,newfullpath)
if len(sys.argv) < 2:
print "Usage: {} directory_name".format(sys.argv[0])
sys.exit()
directory = sys.argv[1]
csvfiles = [ os.path.join(directory,f) for f in os.listdir(directory) if (os.path.isfile(os.path.join(directory,f)) and f.endswith('.csv')) ]
for f in csvfiles:
rename_csv_file(f)
导入csv
导入系统
导入操作系统
def rename_csv_文件(文件名):
全局目录
打开(文件名,'r')作为csv_文件:
newfilename=str()
rownum=0
filereader=csv.reader(csv_文件,分隔符=',')
对于filereader中的行:
如果rownum==0:
newfilename=行[1]。拆分()[1][:2]
elif rownum==1:
newfilename+=行[2][:3]
newfilename+=行[3][:3]
打破
rownum+=1
newfilename+='.csv'
newfullpath=os.path.join(目录,newfilename)
重命名(文件名,newfullpath)
如果len(系统argv)<2:
打印“用法:{}目录\名称”。格式(sys.argv[0])
sys.exit()
directory=sys.argv[1]
csvfiles=[os.path.join(directory,f)for f in os.listdir(directory)if(os.path.isfile(os.path.join(directory,f))和f.endswith('.csv'))]
对于csvfiles中的f:
重命名csv文件(f)
这确实不太复杂。Python提供了您所需的一切现成功能。我认为重命名文件不是一个好主意,如果出现错误(例如冲突),这会使过程变得危险,复制到另一个文件夹更安全。
代码可能如下所示:
import csv
import os
import os.path
import sys
import shutil
def Process(input_directory, output_directory, filename):
"""This methods reads the file named 'filename' in input_directory and copies
it to output_directory, renaming it."""
# Read the file and extract first 2 lines.
with open(filename, 'r') as csv_file:
reader = csv.reader(csv_file, delimiter=',')
line1 = reader.next()
line2 = reader.next()
line1_second_cell = line1[1]
# split() separate words by spaces into a list, [1] takes the second.
second_word = line1_second_cell.split()[1]
line2_third_cell = line2[2]
line2_fourth_cell = line2[3]
# [:2] takes the first two characters from a string.
new_filename = second_word[:2] + line2_third_cell[:3] + line2_fourth_cell[:3]
new_filename += '.csv'
print 'copying', filename, 'to', new_filename
shutil.copyfile(
os.path.join(input_directory, filename),
os.path.join(output_directory, new_filename))
# sys.argv is the list of arguments passed on the command line.
if len(sys.argv) == 3:
input_directory = sys.argv[1]
output_directory = sys.argv[2]
# os.listdir gives all the files in the directory (including ., .. and sub
# directories).
for filename in os.listdir(input_directory):
if filename.endswith(".csv"):
Process(input_directory, output_directory, filename)
else:
print "Usage:", sys.argv[0], "source_directory target_directory"
在windows上,您可以在命令行(cmd.exe)中运行它:在linux上,由于python二进制文件位于路径中,因此会稍微简单一些:
python /where_your_script_is/renamer.py /input /output
这假设目录中的每个csv都需要重命名。代码可以更简洁,但我试着把它拼出来一点,这样你就可以看到发生了什么
import os
import csv
import shutil
#change this to the directory where your csvs are stored
dirname = r'C:\yourdirectory'
os.chdir(dirname)
for item in os.listdir(dirname): #look through directory contents
if item.endswith('.csv'):
f = open(item)
r = csv.reader(f)
line1 = r.next() #get the first line of csv
line2 = r.next() #get the second line of csv
f.close()
name1 = line1[1][:2] #first part of your name
name2 = line2[2][:3] #second part
name3 = line2[3][:3] #third part
newname = name1+name2+name3+'.csv'
shutil.copy2(os.path.join(dirname,item),newname) #copied csv with newname
你的问题到底是什么?
python /where_your_script_is/renamer.py /input /output
import os
import csv
import shutil
#change this to the directory where your csvs are stored
dirname = r'C:\yourdirectory'
os.chdir(dirname)
for item in os.listdir(dirname): #look through directory contents
if item.endswith('.csv'):
f = open(item)
r = csv.reader(f)
line1 = r.next() #get the first line of csv
line2 = r.next() #get the second line of csv
f.close()
name1 = line1[1][:2] #first part of your name
name2 = line2[2][:3] #second part
name3 = line2[3][:3] #third part
newname = name1+name2+name3+'.csv'
shutil.copy2(os.path.join(dirname,item),newname) #copied csv with newname