目录
1. 读取文件
- os.getcwd(),读取当前文件路径
1.1 获取文件的上级路径
# 获取当前文件的绝对路径
current_file_path = os.path.abspath(__file__)
# 获取当前文件所在目录的路径
current_dir_path = os.path.dirname(current_file_path)
# 获取上一级目录的路径
parent_dir_path = os.path.abspath(os.path.join(current_dir_path, os.pardir))
# 获取上两级目录的路径
parent_dir_path = os.path.abspath(os.path.join(current_dir_path, os.pardir, os.pardir))
是不是太麻烦了?
简单点的解决方式一:pathlib package
from pathlib import Path
# 获取当前文件的绝对路径
current_file_path = Path(__file__).resolve()
# 获取上一级目录的路径
parent_dir_path = current_file_path.parent
# 获取上两级目录的路径
grandparent_dir_path = current_file_path.parents[1]
# 获取上三级目录的路径
grandparent_dir_path = current_file_path.parents[2]
是不是感觉还不够简单精炼!
一行代码就能解决的上级路径读取:../
# 获取文件的上一级路径
parent_dir_path = os.path.abspath("../")
# 获取文件的上两级路径
grandparent_dir_path = os.path.abspath("../..")
- pandas.read_csv("../dataset/huanhuan.json"),表示读取上一级路径
- pandas.read_csv("../../dataset/huanhuan.json"),表示读取上两级路径下的dataset文件
2. 文件遍历命令:global、os.walk
定义函数,通常出现在循环结构中。
# Description:将一批txt文件的每一段文本保存成独立的文件
import os
import sys
project_path = os.getcwd()
text_path = project_path+'/text'
# read each sentence
def text_split(file_path):
output_name = os.path.basename(file_path).split('.')[0]
global folder_path
folder_path = text_path + '/' + output_name
if not os.path.exists(folder_path):
os.makedirs(folder_path)
with open(file_path ,'r') as f_input:
num = 1
for sentence in f_input:
save_file(sentence, output_name, num)
num +=1
# save each sentence to file
def save_file(sentence, output_name, num):
global folder_path
# file name format
with open(folder_path+'/'+output_name+'_'+str(num).zfill(3)+'.txt', 'w') as f_output:
f_output.writelines(sentence)
if __name__ == '__main__':
for root, dirs, files in os.walk(text_path):
for file in files:
text_split(root+'/'+file)