打印功能仅显示fi的第一行

2024-04-18 06:20:05 发布

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

我只想逐行读取一个文件,并将每一行附加到一个数组中。我以前做过,没有任何问题,我不知道为什么这次不工作!打印功能只显示文件的第一行!! 这是我的密码:

keyword_array = []    
with open('local directory\\C0577785c.txt') as my_keywordfile:
        for keyword in my_keywordfile.readline().strip("[]").strip("'").split(","):
         keyword_array.append( keyword.strip().strip("'").lower())
         print(keyword_array)

此外,以下是文件内容的子集:

C0001396    adam attack stokes
C0001396    Adam Stokes Attacks
C0001396    Adam-Stokes Attacks
C0001396    adam-stokes syndrome
C0001396    adams attack stoke
C0001396    adams stoke syndrome
C0001396    adams stokes attack
C0001396    ADAMS STOKES SYNDROME
C0001396    Adams-Stokes
C0001396    Adams-Stokes Syndrome
C0001396    Adams-Stokes; attack
C0001396    attack; Adams-Stokes
C0001396    attack; Stokes-Adams
C0001396    Attacks, Adam-Stokes
C0001396    Attacks, Stokes-Adams
C0001396    morgagni's disease
C0001396    Morgagni-Adam's Stokes syndrome
C0001396    Morgagni-Stokes-Adams

谢谢你


Tags: 文件myarraykeywordstripstokesattackadam
3条回答

只调用readline()一次,因此只打印一行。你知道吗

在for循环中,您希望对file对象调用.readlines()。不是readline()。readline()只返回第一行,readlines()返回可以迭代的行列表。你知道吗

从文档中:

readlines(...) method of _io.TextIOWrapper instance
    Return a list of lines from the stream.

    hint can be specified to control the number of lines read: no more
    lines will be read if the total size (in bytes/characters) of all
    lines so far exceeds hint.

我还建议不要清除for循环声明中的行。如果在for循环中这样做,它会觉得读起来容易一些。你知道吗

# ....
with open('myfile.txt', 'r') as my_file:
    for raw_line in my_file.readlines():
        cleaned_data = raw_line.lower().strip("'")
        #....

使用嵌套循环读取我的\u关键字文件的行。你知道吗

for line in my_keywordfile.readlines():
    for keyword in line.strip("[]").strip("'").split(","):

相关问题 更多 >