在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()`。

