python读取相对路径txt文件 - current_directory = os
在计算机编程中,我们经常需要从文件中读取数据。Python 是一种功能强大的编程语言,它提供了丰富的库来帮助我们处理各种任务。介绍如何使用 Python 读取相对路径的 txt 文件。通过一个简单的示例来演示如何实现这一目标。
1. 导入所需库
osioosio
import os
import io
2. 获取当前工作目录
os.getcwd()
current_directory = os.getcwd()
3. 拼接文件路径
os.path.join()
file_name = "example.txt"
file_path = os.path.join(current_directory, file_name)
4. 读取文件内容
open()utf-8with
with io.open(file_path, mode="r", encoding="utf-8") as file:
content = file.read()
5. 输出文件内容
最后,我们可以将读取到的文件内容输出到控制台或保存到其他地方。这里我们选择将内容输出到控制台。
print(content)
完整的代码如下:
import os
import io
# 获取当前工作目录
current_directory = os.getcwd()
# 拼接文件路径
file_name = "example.txt"
file_path = os.path.join(current_directory, file_name)
# 读取文件内容
with io.open(file_path, mode="r", encoding="utf-8") as file: 拼多多帮助力入口
content = file.read()
# 输出文件内容
print(content)
通过以上步骤,我们成功地使用 Python 读取了相对路径的 txt 文件。当然,这只是一个简单的示例,实际应用中可能需要根据具体需求进行相应的调整。希望本文能对你有所帮助!