gpt4 book ai didi

python - 在python中获取文件的绝对路径

转载 作者:太空宇宙 更新时间:2023-11-04 08:06:43 25 4
gpt4 key购买 nike

我正在搜索如何在 python 上获取文件的绝对路径,但运气不佳。这是我的代码

import os


directory = raw_input("What's the directory? ")
print "Reading files.."
listing = os.listdir(directory)
for fname in listing:
with open(fname) as f:
if "yes" in f.read():
print f.name
f.close()

我的问题是...列表非常好..但是当 listdir 方法将变量传递给 open 方法时,变量在没有绝对路径的情况下传递,因此它不会读取文件,因为它是读取没有路径的文件..这是错误示例

目录是什么?/家/迭戈/测试读取文件..追溯(最近一次通话): 文件“/home/diego/Documents/progra/python/antivirus/antivirus.py”,第 14 行,位于 以 open(fname) 作为 f:IOError: [Errno 2] 没有这样的文件或目录:'test'

有人可以帮我吗?

谢谢

最佳答案

from os.path import abspath

full_path = abspath(filename)

关于python - 在python中获取文件的绝对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29910988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com