目录
- File
- `1. 工作目录`
- 1.1 `查看当前目录`
- 1.1 `查看目录是否存在`
- `2. 读文件`
- `2. 读文件`
- `3. 写文件`
File
1. 工作目录
1.1 查看当前目录
import os
current_file = os.path.realpath('file_io.ipynb')
print('current file: {}'.format(current_file))
# .py 脚本可使用 __file__
current_dir = os.path.dirname(current_file)
print('current directory: {}'.format(current_dir))
#.py脚本可以使用os.path.dirname(__file__)
data_dir = os.path.join(os.path.dirname(current_dir), 'data')
print('data directory: {}'.format(data_dir))
1.1 查看目录是否存在
print('exists: {}'.format(os.path.exists(data_dir)))
print('is file: {}'.format(os.path.isfile(data_dir)))
print('is directory: {}'.format(os.path.isdir(data_dir)))
2. 读文件
file_path = os.path.join(data_dir, 'simple_file.txt')
with open(file_path, 'r') as simple_file:
for line in simple_file:
print(line.strip())
2. 读文件
file_path = os.path.join(data_dir, 'simple_file.txt')
with open(file_path, 'r') as simple_file:
for line in simple_file:
print(line.strip())
file_path = os.path.join(data_dir, 'simple_file.txt')
simple_file = open(file_path, 'r')
for line in simple_file:
print(line.strip())
simple_file.close()
3. 写文件
new_file_path = os.path.join(data_dir, 'new_file.txt')
with open(new_file_path, 'w') as my_file:
my_file.write('This is my first file that I wrote with Python.')