如何迭代目录中的文件?

2024-09-29 23:23:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经读过其他的答案了,但似乎我还在某个地方犯错误。你知道吗

我要处理给定目录中的所有csv文件。你知道吗

def main(): 
    data = []

    for root, dir, files in os.walk('/Users/me/Documents/ssbm csv/ssbm_stats/'):

        for name in files:

            # only csv files
            if name.endswith(".csv"):

                csvpath = os.path.join(root, name)
                c = csv.reader(csvpath)
                print "processing:", csvpath

                games = makeT(c)

它运行,但它做了错误的事情。它不会使用csv.reader()打开csv文件。你知道吗

def makeT(csvfile):
    for row in csvfile:
        print csvfile
        print row
        print len(row)

输出:

<_csv.reader object at 0x10d3ecde0>
['/']
1

长度不对。csv文件的任何部分都没有斜杠字符;因此我认为它可能与文件名有关。我真的不明白为什么它不能正确地传递文件。你知道吗

知道如何将文件名传递给csv.reader()吗?你知道吗


Tags: 文件csvcsvfilenameinforosdef
2条回答

您需要将实际打开的文件传递给csv.reader

with open(csvpath, 'rb') as csvfile:
    c = csv.reader(csvfile)
    ...

从文件中

csv.reader(csvfile, dialect='excel', **fmtparams)

Return a reader object which will iterate over lines in the given csvfile. csvfile can be any object which supports the iterator protocol and returns a string each time its next() method is called — file objects and list objects are both suitable.

在您的情况下,第一个参数必须是打开的文件

它可以枯萎

csvfile = open(csvpath, 'rb') 
reader = csv.reader(csvfile)

或者

with open(csvpath, 'rb') as csvfile:
    reader = csv.reader(csvfile)

但是第二个是首选的,因为它会自动关闭文件。你知道吗

csvreader对象的其他参数可以包括delimeterquotechar

相关问题 更多 >

    热门问题