文本文件行阅读问题

时间:2016-05-20 11:56:50

标签: python line

我已阅读文件内容并尝试处理和打印每一行。

在此版面中,内容不会出现在新行中,而只会出现在一行中。并且行内容保持重叠,因此只显示最后一行内容。

    with  open('BSE_company_names_1.txt') as f:
            stuff = f.readline()
            print stuff #print content in one line in overlap fashion
            for data in stuff:
                print data # print each character

文件内容类似于

500002  BSE ABB ABB INDIA LIMITED   1
500003  BSE AEGISLOG    AEGIS LOGISTICS LTD.    2
500005  BSE AKARLAMIN   AKAR LAMINATORS LTD.    2
500008  BSE AMARAJABAT  AMARA RAJA BATTERIES LTD.   3
500009  BSE AMBALALSA   AMBALAL SARABHAI ENTERPRISES L  3
500010  BSE HDFC    HOUSING DEVELOPMENT FINANCE CO  3
500012  BSE ANDHRAPET   ANDHRA PETROCHEMICALS LTD.  2
500013  BSE ANSALAPI    ANSAL PROPERTIES & INFRASTRUCT  2
500014  BSE APPLEFIN    APPLE FINANCE LTD.  2
500016  BSE ARUNAHTEL   ARUNA HOTELS LTD.   2
500020  BSE BOMDYEING   BOMBAY DYEING & MFG.CO.LTD. 2
500023  BSE ASIANHOTNR  ASIAN HOTELS (NORTH) LIMITED    2
500024  BSE ASSAMCO ASSAM COMPANY (INDIA) LIMITED   2
500025  BSE ASSAMBR ASSAMBROOK LTD. 1
500027  BSE ATUL    ATUL LTD.   2
500028  BSE ATVPR   ATV PROJECTS INDIA LTD. 1
500029  BSE AUTOLITIND  AUTOLITE (INDIA) LTD.   1
500030  BSE AUTORIDFIN  AUTORIDERS FINANCE LTD. 2
500031  BSE BAJAJELEC   BAJAJ ELECTRICALS LTD.  2
500032  BSE BAJAJHIND   BAJAJ HINDUSTHAN SUGAR LIMITED  2
500033  BSE FORCEMOT    FORCE MOTORS LTD.   2
500034  BSE BAJFINANCE  BAJAJ FINANCE LIMITED   2
500036  BSE BALAJIIND   BALAJI INDUSTRIAL CORPORATION   2
500037  BSE BALMERL-B   BALMER LAWRIE FREIGHT CONTAINE  2
500038  BSE BALRAMCHIN  BALRAMPUR CHINI MILLS LTD.  2

问题是什么以及如何解决。

我想阅读每一行并拆分每个值

1 个答案:

答案 0 :(得分:1)

您需要readlines而不是readline

with open(...) as f:
    for line in f.readlines():
        for data in line.split():
            ....