当我已经有了能够在本地就好读取文件python程序文件未找到:蟒蛇:使用绝对路径
在我有这个程序的目录,有一个名为路径列表文件(这是一个列表文件路径),我可以打开和访问它,像这样:
test_explicit = open('path_list').read()
print 'Reading local file gives: ' + test_explicit
然后该程序通过这些路径将循环,并调用下面的函数每条路径上,根据其发现的在做事情上面的版本目录。不幸的是,当我拥有绝对路径而不是相对路径时,这些相同的开放/读取操作会给出'没有这样的文件或目录'错误。 (但是,当我打印出它想去的地方并在那里时,我看到了我期望的内容)。
这里是我的代码的相关部分:
def getCommand(path):
# grab that trailing /version, strip the v, convert to int
split_path = path.split("/")
version = split_path.pop()
version_num = int (version[1:])
# increment that number, and remake path with a fresh /v(x+1) suffix
version_num += 1
new_suffix = '/v' + str(version_num)
higher_file_path = '/'.join(split_path)
higher_file_path += new_suffix
finished_filename = 'finished.txt'
finished_filepath = os.path.join(higher_file_path, finished_filename)
result = open(finished_filepath).read()
print 'Result is: ' + result
[more code]
当我运行它,我上线的故障与open
和read()
:
IOError: [Errno 2] No such file or directory: '~/scripts/test/ABC/v4/finished.txt'
但是,当我ls
或cd
有我确实看到文件。
'〜'由OS shell扩展。函数'read()'不使用shell来打开文件,也不能执行扩展。您必须首先将以'〜'开头的路径转换为绝对路径。 – DyZ
我错了 - 那是 - 谢谢你! –