【问题标题】:Concatenating a string to the result of input()将字符串连接到 input() 的结果
【发布时间】:2011-05-02 12:37:02
【问题描述】:

我想在命令行中做这样的事情:

Enter input filename: filename

当用户指定文件名时,应该会发生这种情况

lines = [line.strip() for line in open('filename.txt')]

我尝试过使用

lines = [line.strip() for line in open('input().txt')]

但它只是查找名称为“input().txt”的文件

我怎样才能做到这一点?

谢谢

【问题讨论】:

  • open('input().txt') - 嗯?听说过变量和字符串的区别吗?

标签: python command-line-arguments


【解决方案1】:

您需要将input() 放在引号之外,然后使用+ 运算符将其与'.txt' 连接起来。此外,获取文件名、打开文件和在单独的行中读取文件会增加代码的清晰度。

filename = input()
with open(filename + '.txt', 'r') as f:
    lines = [line.strip() for line in f]

另外,如果您不使用 Python 3,您可能指的是 raw_input 而不是 input

【讨论】:

  • 嗨,当我在 shell 中运行程序时它可以工作,但是当我尝试在命令行中运行它时会产生错误。你能告诉我为什么它在 shell 中运行而不是在命令行中运行。
  • 你确定它真的出错了吗?它可能只是在做它应该做的非常快的事情。
  • IOError: (errno 22) Invalid argument data\r.txt
  • @Jay 尝试输入data/r.txt
  • 嗨,显然它是版本 32 中的一个已知错误。回车添加到输入字符串的末尾。在我添加 rstrip() 后它现在可以工作了
【解决方案2】:

尝试格式化字符串:

open('{0}.txt'.format(input(), 'r'))

您不能直接从字符串内部调用函数,因此必须先调用该函数,然后围绕结果生成字符串。

【讨论】:

    【解决方案3】:

    试试这个:

    lines = [ line.strip() for line in open(raw_input("Enter input filename: ")) ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-28
      • 1970-01-01
      • 2012-03-27
      • 1970-01-01
      • 1970-01-01
      • 2021-11-03
      相关资源
      最近更新 更多