在Python中打开文件时,路径的写法有以下几种:
绝对路径
使用绝对路径打开文件,例如:
file_path = r'C:\Users\Administrator\Desktop\file.txt'
with open(file_path, 'r') as file:
content = file.read()
print(content)
注意路径中的斜杠需要使用`\`,并且前面要加`r`表示原始字符串,避免转义。
相对路径
相对路径是相对于当前工作目录的文件路径。你可以使用`os.path.join()`来连接路径部分,例如:
import os
file_path = os.path.join('directory', 'file.txt')
with open(file_path, 'r') as file:
content = file.read()
print(content)
或者使用`pathlib.Path`类来处理路径:
from pathlib import Path
file_path = Path('directory/file.txt')
with open(file_path, 'r') as file:
content = file.read()
print(content)
用户输入
你也可以通过`input()`函数从用户那里获取文件路径,例如:
file_path = input('Enter the file path: ')
with open(file_path, 'r') as file:
content = file.read()
print(content)
请确保输入的路径是正确的,否则可能会导致文件读取失败。