0

我正在学习文件输入/输出,我想知道如何打开多个具有相似名称的文件。例如 hw-data-01 、 hw-data-02 .....hw-data-99,我需要打开这些文件并处理它们,但我根本无法打开它们。这是我尝试过的,

i = 00
while i < 100 :
    f = open("hw09-data-%d.csv", "r") % i
    for line in f :
        print line
    i = i + 1

问题是当我点击运行查看是否所有文件都被读取和打印时,它说找不到目录。我很确定它是因为 00 + 1 = 1 而不是 01 这是存储文件的方式。我现在不确定该怎么做,我听到我的老师在谈论,glob module但他做了一个非常简短的例子,我不知道如何在这里应用它。任何帮助,将不胜感激

4

3 回答 3

4

Two problems with this code:

open("hw09-data-%d.csv", "r") % i

First of all, you're trying to apply the string formatting operator % to the file object that open() returns. You mean to be applying it to the filename string:

open("hw09-data-%d.csv" % i, "r")

Secondly, you mention filenames with two digit numbers, like hw-data-01. "%d" % 1 is going to return "1" though, not "01" as you want. To fix this, you need to specify that you want a two-digit, zero-padded format, with "%02d"

open("hw09-data-%02d.csv" % i, "r")

Additional notes / critiques:

i = 00

You probably did this to try and fix your previous bug. But this accomplishes nothing in that way. In fact, this could be misleading if it weren't zero, because numbers that start with a leading zero are interpreted in octal. For example 0777 is actually the decimal number 511.

This is Python, not C! Iterate like a Python master:

for i in xrange(10):
    with open("hw09-data-%02d.csv" % i, "r") as f:
       for line in f :
           print line
于 2013-11-03T05:37:45.327 回答
2

glob 模块非常方便,我建议阅读它并使用它来学习如何使用它。这是成为一名优秀程序员的重要组成部分,能够阅读文档并应用新材料。

既然你提到了一位老师,我认为这是家庭作业,所以我不会给你答案。然而,这里有一个简单的例子:

>>> import glob
>>> myfiles = glob.glob('2013-07-*.TCX')

>>> myfiles
['2013-07-27-090736.TCX', '2013-07-28-120243.TCX', '2013-07-28-123000.TCX', '2013-07-29-134417.TCX', '2013-07-29-141027.TCX', '2013-07-30-112848.TCX', '2013-07-30-115900.TCX', '2013-07-30-131222.TCX']

Glob 使用模式匹配来获取与您发送的字符串匹配的所有文件。在这种情况下,我有一个包含日期文件的目录,并且我想要一个 2013 年 7 月以来所有文件的列表。Glob 将获取每个以“2013-07-”开头、以“.TCX”结尾的文件名,并且具有 (基本上)介于两者之间的任何东西。如果您的文件没有那么整齐地标记,您可能需要一个更高级/更具体的模式,但这是基本思想。祝你好运!

于 2013-11-03T08:59:39.330 回答
-1

如果您希望文件名是 00, 01, ... 09, 10, 11, ... 99,您可以试试这个:

i = 00
while i < 10 :
    if i<10 :
        f = open("hw09-data-0{0}.csv".format(i))
    else :
        f = open("hw09-data-{0}.csv".format(i))
    for line in f :
        print line
    i = i + 1
于 2013-11-03T05:42:37.667 回答