在Python中,当你使用`open()`函数打开一个文件时,文件路径可以是相对路径或绝对路径。默认情况下,Python会在当前工作目录中寻找文件。你可以通过以下方法查看或修改当前工作目录:
1. 查看当前工作目录:
```python
import os
print(os.getcwd())
2. 修改当前工作目录:
```python
os.chdir('c:\\') Windows系统下的路径分隔符
如果你需要打开的文件不在当前工作目录中,你可以指定文件的绝对路径或相对路径。例如,如果你有一个文件位于当前工作目录的子目录中,你可以这样指定路径:
```python
相对路径,假设文件位于当前工作目录下的 'data' 子目录中
file_path = 'data/myfile.txt'
with open(file_path, 'r') as file:
content = file.read()
或者使用绝对路径:
```python
绝对路径
file_path = r'C:\Users\username\Documents\myfile.txt'
with open(file_path, 'r') as file:
content = file.read()
请注意,Windows系统中的路径分隔符是反斜杠`\`,但在Python字符串中,反斜杠需要转义,所以通常使用双反斜杠`\\`或者原始字符串(在字符串前加`r`),如`r'C:\Users\username\Documents\myfile.txt'`。