【问题标题】:Reading file from variable in Python [closed]从Python中的变量读取文件[关闭]
【发布时间】:2014-06-30 03:10:58
【问题描述】:

我正在尝试通过变量读取文件的内容

file  = '/home/ec2-user/abc.txt'
paths  = open("file","r+")
print paths.read()

但这不起作用。我需要帮助;我不想直接指定'abc.txt'

【问题讨论】:

  • "file" 是一个字符串,而不是变量引用。想一想。

标签: python linux python-2.7 scripting


【解决方案1】:

首先,您需要删除"file"周围的引号:

paths = open(file,"r+")

当您使用变量的值调用某些内容时,您不应引用该变量。

其次,如果您不想硬编码file 的路径,则需要向用户询问:

file = raw_input("Please enter the full path to the file: ")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 2018-08-04
    • 2013-03-13
    • 2010-09-06
    • 1970-01-01
    • 1970-01-01
    • 2014-06-26
    相关资源
    最近更新 更多