在python中一次读取多个文件

我用python编写了一个代码,它读取文件的单个列,并根据我给出的if/else条件将输出给出为“P”或“R”。我想更改它,使其在获得第一个P或R的那一刻停止读取文件并将其打印为输出。另外,我有一千个这样的文件,所以我每次运行它时都必须不断更改文件名。任何人都可以对此代码进行更改,以便我可以立即运行它并获得所有文件的输出?所有此类文件都位于同一目录中,并且这些文件是目录中的唯一文件。任何人都可以告诉我如何存储或打印相应文件的输出?


    f = open('/home/abc/xyz/coord/coord_348.xvg')



    dat = f.readlines()

    dat1 = dat[22:len(dat)]

    dat2=[]

    for k in dat1:

        dat2.append(k.split())

    res=[]

    for k in dat2:

        if float(k[1])>=9.5:

          print('P')

          res.append

        elif float(k[1])<=5.9:

          print('R')

          res.append

        else:

          res.append


    print(res)


炎炎设计
浏览 108回答 1
1回答

慕的地10843

因此,您最初可以简化循环,如下所示:with open("file.xvg", "r") as f:&nbsp; &nbsp; for i, line in enumerate(f):&nbsp; &nbsp; &nbsp; &nbsp; if i < 22:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # Skip up to line 22&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; &nbsp; &nbsp; line = line.strip().split()&nbsp; &nbsp; &nbsp; &nbsp; # It isn't clear what you want to append to `res`&nbsp; &nbsp; &nbsp; &nbsp; if float(line[1]) >= 9.5:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("P")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; elif float(line[1]) <= 5.9:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("R")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("N")这将分析文件,而不是将其读取到列表中并分析列表。break 语句将您带出通过文件的循环。如果目录中有许多文件,则可以像这样阅读它们:from pathlib import Pathfor file in Path("/path/to/directory").rglob("*.xvg"):&nbsp; &nbsp; with file.open("r") as f:&nbsp; &nbsp; &nbsp; &nbsp; for i, line in enumerate(f):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # Same logic as above&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pass
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python