【问题标题】:How to read file from the command line on Mac terminal for Python如何从 Python 的 Mac 终端上的命令行读取文件
【发布时间】:2021-05-22 04:52:46
【问题描述】:

如何读取文件(.in 格式)并将其应用于我的 .py Python 程序?

例如,我的python代码标题为Add_4.py

import sys
main():
    num = int(sys.stdin.readline().strip())
    final_output = num + 4
    print(final_output)
if __name__ == "__main__":
    main()

文本文件的标题将是Numbers.in

5
18
-3

我相信我必须在终端中使用“

【问题讨论】:

  • 您想读取并打印“.in”文件每一行中的数字+4吗?从命令提示符?对吗?
  • @SANGEETHSUBRAMONIAM 是的!我意识到我写的代码完全错误,它无法正常运行,但你问的是我想要实现的目标。

标签: python macos pycharm


【解决方案1】:

假设你有文件add4.py,内容:

import sys
def main():
    num = int(sys.stdin.readline().strip())
    final_output = num + 4
    print(final_output)
if __name__ == "__main__":
    main()

你有明文文件Numbers.in,内容:

5
18
-3

您可以使用|(管道)或使用<(从文件中读取标准输入)将Numbers.in 的内容通过管道或重定向到add4.py

示例 1:

$ cat Numbers.in | python add4.py
9

示例 2:

$ python add4.py < Numbers.in
9

请注意,由于 Python 代码的编写方式,仅读取第一行(编号 5),然后添加 4 成为 9


如果您想读取多行并期望输出类似

9
22
1

那么你应该使用readlines 而不是readline

文件add4all.py,内容:

import sys
def main():
    lines = sys.stdin.readlines()
    for num in lines:
        final_output = int(num) + 4
        print(final_output)
if __name__ == "__main__":
    main()

那么结果是:

$ python add4all.py < Numbers.in 
9
22
1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-15
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    • 2016-05-09
    相关资源
    最近更新 更多