Python:循环遍历多个csv文件并创建多个新的csv文件

3
我正在学习Python,并且正在查看csv文件。
基本上我的情况是这样的:
我在一个csv文件中有X、Y、Z坐标。
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"附加到末尾。
我认为我需要使用"os."函数,但我不确定应该怎么做,所以带有代码的任何解释都将受到赞赏! :)
如果我表达不清楚,请告诉我。 :)
非常感谢! :)

1
module glob会在这种情况下有所帮助。 - The6thSense
2个回答

2
shutil.copy2(src, dst)¶
Similar to shutil.copy(), but metadata is copied as well

shutil

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 

glob

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 file[:4]这会从字符串中删除最后4个字符。它将删除".csv",因为我们需要附加"_offset.csv"。 - LetzerWille
太好了,谢谢你。这是一个很方便的小技巧要知道。 :) - FactorV

1
顺便提一句,你可以写...
for row in reader:
    if row[0] == "X":
        break
for row in reader:
    coord = []
    ...

... 而不是 ...

for row in reader:
    if row[0] != "X": 
        coord = []
        ...

这将在第一行后停止检查 'X'。它能够工作是因为你在这里不是使用真正的列表,而是使用一个自我消耗的 迭代器,你可以停止和重新开始。
另请参阅:检测迭代器是否会被消耗

太棒了,谢谢Nils,这样读起来更有意义和流畅 :) - FactorV

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接