在Python中修改文件路径通常涉及到以下几个步骤:
获取当前工作目录
import os
current_dir = os.getcwd()
print("当前工作目录:", current_dir)
更改当前工作目录
new_dir = "/path/to/new/directory"
os.chdir(new_dir)
创建新的文件路径
original_file = "/path/to/original/file.txt"
new_directory = "/path/to/new/directory"
new_file = os.path.join(new_directory, "new_file.txt")
print("新的文件路径:", new_file)
使用`os.rename()`函数移动文件
file_path = "C:/path/to/original/file.txt"
save_path = "D:/path/to/new/location/file.txt"
file_name, file_ext = os.path.splitext(file_path)
new_file_path = os.path.join(save_path, os.path.basename(file_name) + file_ext)
os.rename(file_path, new_file_path)
使用`os.environ`设置存储路径 (例如,设置环境变量`PATH`):
new_directory = "/path/to/new/directory"
os.environ["PATH"] = new_directory
下载文件并指定路径
import os
from urllib.request import urlretrieve
url = "https://example.com/file.txt"
download_path = "C:/Users/username/Downloads/"
os.chdir(download_path)
urlretrieve(url, "file.txt")
或者使用`requests`模块下载文件并指定路径:
import requests
url = "https://example.com/file.txt"
download_path = "C:/Users/username/Downloads/"
response = requests.get(url)
with open(download_path + "file.txt", "wb") as file:
file.write(response.content)