在Python中,读取文件地址通常指的是获取文件的路径,然后使用文件路径来读取文件内容。以下是获取文件路径和读取文件内容的方法:
获取文件路径
```python
import os
获取当前工作目录
current_directory = os.getcwd()
print("当前工作目录:", current_directory)
获取指定文件的绝对路径
file_path = "path/to/your/file.txt"
print("文件路径:", file_path)
读取文件内容
```python
使用open()函数打开文件并读取其内容
file_path = "path/to/your/file.txt"
try:
with open(file_path, "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("文件未找到")
使用`io`模块
```python
import io
使用io模块的io.open()函数打开文件并读取其内容
file_path = "path/to/your/file.txt"
try:
with io.open(file_path, "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("文件未找到")
以上代码展示了如何使用`os`模块获取文件路径,以及如何使用`open`函数和`io`模块读取文件内容。请确保替换`file_path`变量的值为实际文件的路径