在Python中读取文件路径通常涉及以下几个步骤:
1. 获取文件路径
2. 检查路径是否存在
3. 读取文件内容
import os
获取用户输入的文件路径
file_path = input("请输入文件路径:")
检查路径是否存在
if os.path.exists(file_path):
读取文件内容
try:
with open(file_path, 'r') as file:
content = file.read()
print(content)
except FileNotFoundError:
print("文件未找到。")
except Exception as e:
print("发生错误:", e)
else:
print("路径不存在。")
import os
获取当前工作目录
current_directory = os.getcwd()
获取当前工作目录下的文件路径
file_path = os.path.join(current_directory, "name.txt")
检查路径是否存在
if os.path.exists(file_path):
读取文件内容
try:
with open(file_path, 'r') as file:
content = file.read()
print(content)
except FileNotFoundError:
print("文件未找到。")
except Exception as e:
print("发生错误:", e)
else:
print("路径不存在。")
如果你需要将相对路径转换为绝对路径,可以使用`os.path.abspath()`函数:
import os
获取相对路径
relative_path = "path/to/your/file.txt"
转换为绝对路径
absolute_path = os.path.abspath(relative_path)
检查路径是否存在
if os.path.exists(absolute_path):
读取文件内容
try:
with open(absolute_path, 'r') as file:
content = file.read()
print(content)
except FileNotFoundError:
print("文件未找到。")
except Exception as e:
print("发生错误:", e)
else:
print("路径不存在。")
请根据你的具体需求选择合适的方法来读取文件路径。