有没有一种方法可以让我在编码时不必为我使用的任何文件提供绝对路径名?
Is there a way by which I don't have to give the absolute pathname for any file I use while coding?
每当我处理一个文件时,无论是读取还是修改它,每次我在编码时都必须使用它的绝对路径名。
例如:
fname = open(C:\Users\aaa\Downloads\Dummyfile.txt, r)
有没有一种方法可以让我每次在代码中使用它时只使用文件名而不是使用绝对路径名?
例如:
fname = open(Dummyfile.txt, r)
谢谢。
使用变量并将其设置为路径:
from os.path import join
mypath = "C:/Users/aaa/Downloads/"
with open(join(mypath,"Dummyfile.txt"), "r") as f:
a = f.read()
或者如果你总是使用 Dummyfile.txt:
mypath = "C:/Users/aaa/Downloads/Dummyfile.txt"
with open(mypath, "r") as f:
a = f.read()
每当我处理一个文件时,无论是读取还是修改它,每次我在编码时都必须使用它的绝对路径名。
例如:
fname = open(C:\Users\aaa\Downloads\Dummyfile.txt, r)
有没有一种方法可以让我每次在代码中使用它时只使用文件名而不是使用绝对路径名?
例如:
fname = open(Dummyfile.txt, r)
谢谢。
使用变量并将其设置为路径:
from os.path import join
mypath = "C:/Users/aaa/Downloads/"
with open(join(mypath,"Dummyfile.txt"), "r") as f:
a = f.read()
或者如果你总是使用 Dummyfile.txt:
mypath = "C:/Users/aaa/Downloads/Dummyfile.txt"
with open(mypath, "r") as f:
a = f.read()