【问题标题】:How can I print more than one line of a file using python?如何使用 python 打印多行文件?
【发布时间】:2016-06-01 15:04:08
【问题描述】:

每当我尝试使用我的 python 程序读取文件时,在命令停止之前我只会得到一行。我很确定它与print(line) 有关,但我不知道任何其他选择。到目前为止,这是我所拥有的:

def fopen():
    file = input("Open: ")
    print("")
    with open(file, 'r') as f:
        for line in f:
            print(line)
            print("")
            editredirect()

def editredirect():
    print("You can edit this file with the 'edit' command.")
    dcmdLvl2()

dcmdLcl2() 只是为了让我回到我的命令行。

【问题讨论】:

  • 我看不出有什么问题。 dcmdLvl2 是做什么的?
  • editredirect() 是做什么的?
  • 我认为您需要取消缩进 editredirect() 以与 with 对齐

标签: python file-io input io


【解决方案1】:

由于缩进,您的editredirect() 在循环内。 尝试删除缩进并将editredirect()(可能还有print(""))移出循环。

【讨论】:

    【解决方案2】:

    你想为文件中的每一行打印"You can edit this file..."吗?应该不会吧……

    另外,如果dcmdLvl2() 出于某种原因退出脚本,那么是的,您只会看到文件的一行。

    尝试取消缩进editredirect()

    def fopen():
        file = input("Open: ")
        print("")
        with open(file, 'r') as f:
            for line in f:
                print(line)
                print("")   # new line?
        editredirect()
    
    def editredirect():
        print("You can edit this file with the 'edit' command.")
        dcmdLvl2()
    

    【讨论】:

      【解决方案3】:

      你在读完一行后重定向到命令行,你应该从for循环中删除editredirect

      def fopen():
         file = input("Open: ")
         print("")
         with open(file, 'r') as f:
            for line in f:
                print(line)
                print("")
         editredirect()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-02-13
        • 2016-09-02
        • 1970-01-01
        • 2018-12-25
        • 2018-03-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多