【发布时间】:2017-07-15 18:25:49
【问题描述】:
我有一个 Python 程序可以很好地在本地读取文件:
在我有这个程序的目录中,有一个名为 path_list 的文件(它是一个文件路径列表),我可以像这样打开和访问它:
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 来打开文件并且不能进行扩展。您必须先将以“~”开头的路径转换为绝对路径。 -
我错了-是的-谢谢!
标签: python