代码之家  ›  专栏  ›  技术社区  ›  lampShadesDrifter

文件readline()不返回任何内容,即使知道有行内容

  •  0
  • lampShadesDrifter  · 技术社区  · 4 年前

    尝试读取文件的某些行 here )即使我可以计算文件的行数 readline() 方法似乎没有返回任何内容。

    下面的代码片段(我有额外的代码,显示了我最初是如何将这些文件读入系统的(通过FTP下载 ftplib )以防与问题有关(因为我真的不知道是什么导致了这种奇怪)。这个 with open(localname)... 靠近底部的那条线是我开始试着读这些线的地方。

    # connect to ftp location
    ftp = ftplib.FTP(MY_IP)
    ftp.login(CREDS["source"]["ftp_creds"]["username"], CREDS["source"]["ftp_creds"]["password"])
    print(ftp.pwd())
    print(ftp.dir())
    ftp.cwd(CONF["reporting_configs"]["from"]["share_folder_path"])
    print(ftp.pwd())
    print(ftp.dir())
    
    # download all files from ftp location
    print(f"Retrieving files from {CONF['reporting_configs']['from']['share_folder_path']}...")
    files = ftp.nlst()
    files = [f for f in files if f not in ['.', '..']]
    pp.pprint(files)
    for f in files:
        # timestamp = int(time.time())
        # basename = os.path.split(f)[0]
        localname = os.path.join(CONF["stages_base_dir"], CONF["stages"]["imported"], f"{f}")
        fd = open(localname, 'wb')
        ftp.retrbinary(f"RETR {f}", callback=fd.write)
        fd.close()
        SAMPLE_LINES = 5
        with open(localname) as newfile:
            print(f"Sampling {newfile.name}")
            for i, _ in enumerate(newfile):
                pass
            lines = i+1
            print(lines)
            for i in range(min(SAMPLE_LINES, lines)):
                l = newfile.readline()
                print(l)
    

    输出看起来像。。。

    <after some other output>
    .
    .
    .
    Retrieving files from /test_source...
    ['TEST001.csv', 'TEST002.csv']
    Sampling /path/to/stages/imported/TEST001.csv
    5
    
    
    
    
    
    Sampling /path/to/stages/imported/TEST002.csv
    5
    
    
    
    
    
    
    

    请注意,它能够识别每个文件中的行数超过0行,但是打印 阅读线()

    1 回复  |  直到 4 年前
        1
  •  2
  •   Ollie Pugh    4 年前

    在我的机器上测试后,如果你添加 newfile.seek(0) 要将指针重置回文件的开头,它可以工作。

    SAMPLE_LINES = 5
    with open("test.txt") as newfile:
        print(f"Sampling {newfile.name}")
        for i, _ in enumerate(newfile):
            pass
        lines = i+1
        print(lines)
        newfile.seek(0)
        for i in range(min(SAMPLE_LINES, lines)):
            l = newfile.readline()
            print(l)
    

    我认为这可以修复它的唯一原因是当您使用 enumerate(newfile) 该函数本身正在使用新文件.readline()函数,因此正在移动指针。