我对python不太熟悉,谁能告诉我如何使用python中的变量打开文件? 我想在脚本中自动执行此操作,以跨多个目录运行相同的任务
这里机器和输入文件是变量.. 我尝试了以下代码,但不断出现错误
file = open(machine + '/' + inputfile)
打印效果很好.. 即变量已正确填充:
print 'Input file is "', inputfile -> abc
print 'Machine "', machine -> xyz
因此文件位置应该是./xyz/abc
错误: 我得到的错误是文件 ./machine/inputfile 不存在,即不是采用变量 machine 和 inputfile 的值,而是按原样采用它们。
如果这个问题太微不足道,我深表歉意
最佳答案
一般来说,您的代码没有任何问题。您的路径和/或文件名可能有问题。
这就是我的做法(在 Windows 上)
import os
dir='C:/Users/xxx' # You can use forward slashes on Windows
file='somefile.txt'
full_path=os.path.join(dir,file) # OS independent way of building paths
with open(full_path,'r') as f: # 'with' will automatically close file for you,
for line in f: # Do something with the file
print line
关于python - 使用变量python脚本打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26117130/