Python:通过多个csv文件循环并制作多个新的csv文件
我刚开始使用Python,并且正在查看csv文件。Python:通过多个csv文件循环并制作多个新的csv文件
基本上我的情况是这样的:
我有坐标X,Y,Z在CSV。
X Y Z
1 1 1
2 2 2
3 3 3
我想通过并为所有Z值添加一个用户定义的偏移值,并创建一个带有编辑的z值的新文件。
这里是迄今为止,我认为我的代码是正确的:
# list of lists we store all data in
allCoords = []
# get offset from user
offset = int(input("Enter an offset value: "))
# read all values into memory
with open('in.csv', 'r') as inFile: # input csv file
reader = csv.reader(inFile, delimiter=',')
for row in reader:
# do not add the first row to the list
if row[0] != "X":
# create a new coord list
coord = []
# get a row and put it into new list
coord.append(int(row[0]))
coord.append(int(row[1]))
coord.append(int(row[2]) + offset)
# add list to list of lists
allCoords.append(coord)
# write all values into new csv file
with open(in".out.csv", "w", newline="") as f:
writer = csv.writer(f)
firstRow = ['X', 'Y', 'Z']
allCoords.insert(0, firstRow)
writer.writerows(allCoords)
但现在来的最困难的部分。我将如何处理一堆csv文件(位于同一位置),并为每个csv生成一个新文件。
我希望能有这样的东西:“filename.csv”变成“filename_offset.csv”使用原始文件名作为新文件名的起始者,在末尾附加“.offset”。
我想我需要使用“操作系统”。功能,但我不知道如何,所以任何解释将与代码非常赞赏! :)
对不起,如果我没有什么意义,让我知道如果我需要更清楚地解释。 :)
谢谢一堆! :)
shutil.copy2(src, dst)¶
Similar to shutil.copy(), but metadata is copied as well
The glob module finds all the pathnames matching a specified pattern
according to the rules used by the Unix shell. No tilde expansion is
done, but *, ?, and character ranges expressed with [] will be correctly matched
import glob
from shutil import copy2
import shutil
files = glob.glob('cvs_DIR/*csv')
for file in files:
try:
# need to have full path of cvs_DIR
oldName = os.path.join(cvs_DIR, file)
newName = os.path.join(cvs_DIR, file[:4] + '_offset.csv')
copy2(oldName,newName)
except shutil.Error as e:
print('Error: {}'.format(e))
真棒,感谢Letzer。快速的问题,所以我明白。在newName变量中,什么是“[:4]”? – FactorV
@FactorV文件[:4]从字符串中删除最后4个字符。它会删除.csv,因为我们需要附加_offset.csv – LetzerWille
太好了,谢谢你。它是一个方便的小知识。 :) – FactorV
'模块glob'会在这种情况下帮助 – The6thSense