【问题标题】:How to read input() from a text file in Python如何在 Python 中从文本文件中读取 input()
【发布时间】:2019-12-03 14:36:06
【问题描述】:

我的 Python 程序请求一些用户输入:

n = int(input())
for i in range(n):
    s = input()
    # ...

出于调试目的,我想创建一个这样的测试 input.txt 文件:

3
string1
string2
string3

这样我每次启动调试时都不需要从键盘手动输入数据。

有什么方法可以从文本文件中获取input(),而不是从键盘获取(不更改程序代码)。

我正在使用 Wing Personal 作为开发工具。

更新

我肯定知道,存在能够测试 python 程序传递各种输入并将输出与已知答案进行比较的机器人。我猜这些机器人不会用铁手指敲击键盘。也许他们使用命令行工具将input.txt 传递给Python,以便它从该文件中读取input(),而不是从键盘中读取。我想学习怎么做。

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    输入从标准输入读取,因此如果您使用 bash,您可以将标准输入重定向到文件

    无需更改代码

    在 bash 中你会运行类似

    的东西
    cat textfile | programm.py
    

    < textfile programm.py
    

    【讨论】:

    • OP 请求 python?
    • 他也问(不改变程序代码)。所以我提供了一种无需接触代码即可更改标准输入的方法
    • 站稳脚跟,我喜欢!
    • 我想你的意思是,cat textfile | python programm.py
    【解决方案2】:

    我注意到这些解决方案都没有从 Python 重定向标准输入。为此,您可以使用这个 sn-p:

    import sys
    sys.stdin = open('input.txt', 'r')
    

    希望对您有所帮助!

    【讨论】:

      【解决方案3】:

      您可以将文件读入如下列表:

       with open('filename.txt', 'r') as file:
           input_lines = [line.strip() for line in file]
      

      s 将是索引 i 中的数据。

      n = int(input())
      for i in range(n):
          s = input_lines[i]
          # ...
      

      确保您的 py 文件与 txt 文件位于同一目录中。

      【讨论】:

        【解决方案4】:

        您可以创建一个test.py 文件,用于运行您的测试。在test.py 中,您将阅读input.txt 的内容并导入编程。

        例如,在test.py 文件中。

        import main_code
        with open('input.txt', 'r') as file:
           lines = file.readlines()
        
        for line in lines:
           s = line
        
        """
        working with the input.
        """ 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-12-18
          • 2020-04-19
          • 1970-01-01
          • 1970-01-01
          • 2018-09-14
          • 2015-05-21
          • 1970-01-01
          • 2018-05-14
          相关资源
          最近更新 更多