打开名字的文件

时间:2017-11-01 21:35:36

标签: python file

当我尝试打开此功能的文件时,我没有得到所有的名字。我想得到这个:

Smith, Joe,9911991199,smithjoe9,99,88,77,66
Ash, Wood,9912334456,ashwood,11,22,33,44
Full, Kare,9913243567,fullkare,78,58,68,88

但是当我测试这个功能时,我得到了这个:

['Ash, Wood,9912334456,ashwood,11,22,33,44\n', 'Full, Kare,9913243567,fullkare,78,58,68,88\n']

任何人都可以帮我解决这个问题吗?我怎样才能包括第一个人的姓名?

def open_grades_file(filename):
    '''(str) -> file

    Open filename, read past its one-line header and
    return the open file.
    '''
    file = open(filename, 'r')
    file.readline()
    for line in file:
        line.rstrip('\n')
        return file

3 个答案:

答案 0 :(得分:2)

如果您希望函数实际对应于其docstring,请使用:

def open_grades_file(filename):
    '''(str) -> file

    Open filename, read past its one-line header and
    return the open file.
    '''
    file = open(filename, 'r')
    file.readline()
    return file

但这是一件非常奇怪的事情,像这样的函数会更加pythonic:

def read_grade_lines(path):
    with open(path) as f:
        for line in f.readlines():
            yield line.strip()

答案 1 :(得分:1)

读取单行标题后的所有文件:

def open_grades_file(filename):
    '''(str) -> (file)

    Open filename, read past its one-line header and
    return file.
    '''
    file = open(filename, 'r')
    file.readline()

    return file

# read all file past its one-line header
f = open_grades_file(filename).read()

print(f)

将打印:

Smith, Joe,9911991199,smithjoe9,99,88,77,66
Ash, Wood,9912334456,ashwood,11,22,33,44
Full, Kare,9913243567,fullkare,78,58,68,88

答案 2 :(得分:1)

如果您只是想将某些内容打印到控制台或需要更新某些变量,我不确定您是否需要返回任何内容,但这个简单的函数会按顺序将所有行打印到控制台。

def open_grades_file(filename):
    with open(filename, 'r') as f:
        for line in f:
            print(line.rstrip('\n'))

如果你能提供更多关于你想要做什么的背景,我可以形成一个更好的答案。

如果你想打印除第一行以外的所有行,你可以使用一个真/假变量来跳过第一行。

这样的事情:

x = False

def open_grades_file(filename):
    global x
    with open(filename, 'r') as f:
        for line in f:
            if x == True:
                print(line.rstrip('\n'))
                return line.rstrip('\n') # this return line should work for you. Though I am not sure what its for in your case.
            else:
                x = True # sets x to true after the first line is read.
    x = False # resets for next use of the function

open_grades_file("data")