我只是为了娱乐而尝试了解是否可以在使用with with语句的同时提取文件的完整路径(Python 3.8)
我有一个简单的代码:
with open('tmp.txt', 'r') as file:
print(os.path.basename(file))
但是我一直遇到一个错误,因为它不是合适的类型格式。
我也一直在尝试使用 relpath
, abspath
,依此类推。
它说输入应该是一个字符串,但是即使将其施加到字符串中,我也得到了无法操纵的东西。
也许没有一种实际方法来提取完整的路径名,但我认为有。我只是找不到。
I'm trying, just for fun, to understand if I can extract the full path of my file while using the with statement (python 3.8)
I have this simple code:
with open('tmp.txt', 'r') as file:
print(os.path.basename(file))
But I keep getting an error that it's not a suitable type format.
I've been trying also with the relpath
, abspath
, and so on.
It says that the input should be a string, but even after casting it into string, I'm getting something that I can't manipulate.
Perhaps there isn't an actual way to extract that full path name, but I think there is. I just can't find it, yet.
发布评论
评论(2)
类似路径的对象。您正在尝试通过a file 而不是。这些类型无法互换的原因很多。
由于您打开了文本读数的文件,因此
file
是io.textiowrapper
。该类只是一个接口,为某些基础数据提供文本编码和解码。它通常与路径没有关联:基础流可以是磁盘上的文件,而是管道,网络套接字或内存缓冲区(例如io.stringio
)。后者都没有以您正在思考的方式与路径或文件名相关联,即使您会通过普通文件对象与它们接口。如果您的file-like是
io.fileio
,它将有一个
name
属性以跟踪跟踪此信息适合您。其他数据来源不会。由于问题中的示例使用fileio
,因此您可以执行完整的文件路径,由
os.path.abspath
。话虽如此,由于文件对象通常不在乎文件名,因此您可以自己跟踪该信息可能更好,以防有一天您决定使用其他内容作为输入。 Python 3.8+允许您在不使用海象操作员更改线数的情况下执行此操作:
The functions in
os.path
accept strings or path-like objects. You are attempting to pass in a file instead. There are lots of reasons the types aren't interchangable.Since you opened the file for text reading,
file
is an instance ofio.TextIOWrapper
. This class is just an interface that provides text encoding and decoding for some underlying data. It is not associated with a path in general: the underlying stream can be a file on disk, but also a pipe, a network socket, or an in-memory buffer (likeio.StringIO
). None of the latter are associated with a path or filename in the way that you are thinking, even though you would interface with them as through normal file objects.If your file-like is an instance of
io.FileIO
, it will have aname
attribute to keep track of this information for you. Other sources of data will not. Since the example in your question usesFileIO
, you can doThe full file path is given by
os.path.abspath
.That being said, since file objects don't generally care about file names, it is probably better for you to keep track of that info yourself, in case one day you decide to use something else as input. Python 3.8+ allows you to do this without changing your line count using the walrus operator:
您可以尝试:
You could try: