如何在读取文件时跳过一行(是:如何索引文件?)

时间:2014-03-28 01:32:59

标签: python string list file

我有必须使用图形库读取和绘制的数据。我能够将数据拆分成一个列表,除了我想跳过第一个列表。

     from graphics import *
    def main():
       data = input("Type in the filename: ")
infile = open(data, "r")


for aline in infile:
    # I try using read() but I get one output 
    data1 = infile.readline() 
    dataLst = aline.split('","')
    print(dataLst[1])
 main()

输出:

     close <--- How to skip this line?
     720.11
     720.1100
     721.0700

以下是数据示例,粗体是我要打印的数据: &#34;日期&#34;&#34;靠近&#34;&#34;体积&#34;&#34;开&#34;&#34;高&#34;&#34;低速& #34;

&#34; 16:00&#34;,的&#34; 720.11&#34; 下,&#34; 1919799&#34;&#34; 720.71&#34; &#34; 723&#34;&#34; 716.68&#34; &#34;十二分之二千零十二/ 19#34;,的&#34; 720.1100&#34; 下,&#34; 1918493.0000&#34;&#34; 720.7100&#34 ;, #&34; 723.0000&#34;&#34; 716.6800&#34; &#34;十二分之二千零一十二/ 18#34;,的&#34; 721.0700&#34; 下,&#34; 3004838.0000&#34;&#34; 716.6000&#34 ;, &#34; 729.1000&#34;&#34; 715.0500&#34;

5 个答案:

答案 0 :(得分:3)

您可以使用next()功能跳过第一行:

with open('data.txt') as f:
    next(f) # Skip one line
    for line in f:
        print line

更新

我不知道为什么原始海报不喜欢next(),但如果PO坚持,请改用readline()

with open('data.txt') as f:
    f.readline() # Skip one line
    for line in f:
        print line

答案 1 :(得分:1)

如果您使用csv module

,您的生活会更轻松
import csv

with open(fn, 'r') as f:
    data=csv.reader(f)
    header=next(data)
    for line in data:
        print line[1]

打印:

720.11
720.1100
721.0700

答案 2 :(得分:1)

如果您在readline()循环之前致电for但未保留其输出,那么该行就会被删除:

infile.readline()
for aline in infile:
    # I try using read() but I get one output 
    data1 = infile.readline() 
    dataLst = aline.split('","')
    print(dataLst[1])

这与在next上调用infile函数基本相同。

答案 3 :(得分:0)

这是一个在Python 2和3中都能正常运行的版本:

import csv
import sys

if sys.hexversion < 0x3000000:
    # Python 2.x
    csv_open_read = lambda fname: open(fname, "rb")
    inp = raw_input
else:
    # Python 3.x
    csv_open_read = lambda fname: open(fname, "r", newline="")
    inp = input

def read_csv(fname, skip_header=False, **kwargs):
    with csv_open_read(fname) as inf:
        if skip_header:
            next(inf, None)
        for row in csv.reader(inf, **kwargs):
            yield row

def main():
    fname = inp("Type in the filename: ").strip()
    closes = [float(row[1]) for row in read_csv(fname, skip_header=True)]

if __name__=="__main__":
    main()

答案 4 :(得分:-3)

你不应该编写这个程序因为它已经存在而且它被称为tail。

$ cat skip
close
720.11
720.1100
721.0700
$ tail -n +2 skip
720.11
720.1100
721.0700

http://www.unix.com/man-page/POSIX/1posix/tail/