在Python中读取桌面上的文件,你可以使用`open()`函数,并指定文件的绝对路径。以下是一个简单的示例代码,展示了如何读取桌面上的文本文件:
获取桌面路径
import os
获取当前用户桌面路径
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
指定文件名
file_name = "example.txt"
拼接文件绝对路径
file_path = os.path.join(desktop_path, file_name)
使用open()函数打开文件,并指定模式为'r'(只读模式)
with open(file_path, 'r', encoding='utf-8') as file:
读取文件内容
content = file.read()
输出文件内容
print(content)
请确保将`example.txt`替换为你桌面上实际的文件名。此代码使用了`with`语句,它会在代码块执行完毕后自动关闭文件,无需显式调用`file.close()`。