【问题标题】:How can I create a program which reads from any text file given?如何创建一个从给定的任何文本文件中读取的程序?
【发布时间】:2020-11-15 19:11:58
【问题描述】:

到目前为止我做了什么:

def readMatrixFile(file):
    '''
    This function reads files
    '''
    fr = open("{}".format(file), 'r') 
    
    # Checking every line whether it is a matrix row or not.
    for line in file:
        print(line)
        
    # close the file
    fr.close()
        

我想创建一个函数来读取给定的任何文件。我上面的代码不起作用。我在哪里做错了什么?我还需要做什么?

【问题讨论】:

  • 应该是for line in fr: 而不是for line in file:

标签: python file-io


【解决方案1】:

这样的东西可能对你有用:

def readMatrixFile(file):
    with open(file, 'r') as f:
        for line in f:
            print(line)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-12
    • 2015-01-29
    • 1970-01-01
    • 2022-01-14
    • 2023-03-04
    • 2019-06-30
    • 1970-01-01
    相关资源
    最近更新 更多