tos os.path 模块
- 获取绝对路径
import os
path = 'x/'
abs_path = os.path.abspath(path)
print(abs_path)
- 拼接路径
sub_path = 'x_sub/'
new_path = os.path.join(path, sub_path)
print(new_path)
- 打开文件夹
path = 'x/'
dirs = os.listdir(path)
for files in dirs:
with open('x2/test_list.txt', "a") as f:
f.write(files + '\n')
f.close()
- 创建文件并读写
content = os.open('x2/test_list2.txt', os.O_RDWR)
file_new = os.open('x2/test_list2.txt', os.O_RDWR | os.O_CREAT)
content = bytes('this is a new txt file \n', encoding="utf8")
os.write(file_new, content)
content2 = bytes('this is the second line', encoding="utf8")
os.write(file_new, content2)
os.close(file_new)
- 创建文件夹,os.mkdir() 和 os.makedirs()区别
new_folder = 'x2/'
if os.path.exists(new_folder):
print('existed')
if not os.path.exists(new_folder):
os.mkdir(new_folder)
new_folder = 'x2/x2_sub/'
if os.path.exists(new_folder):
print('existed')
if not os.path.exists(new_folder):
os.makedirs(new_folder)
folders = ['folder1', 'folder2', 'folder3', 'folder4', 'folder5']
for folder in folders:
isExists = os.path.exists(folder)
if not isExists:
os.makedirs(folder)
print('created folder: %s' % folder)
else:
print('already existed')
- 移除
os.remove('x2/test_list.txt')
- 重命名(oldname, newname),不能更换文件地址。
os.rename('x2/test_list2.txt', 'x2/tt.txt')
- os.walk() 遍历文件夹
a = os.walk('x/')
print(a)
for curDir, dirs, files in a:
for curDir, dirs, files in os.walk('x/'):
with open('record.txt', 'a') as f:
f.write('===============' + '\n')
f.write('现在的目录:' + curDir + '\n')
f.write('该目录下包含的子目录:' + str(dirs) + '\n')
f.write('该目录下包含的文件:' + str(files) + '\n')
f.close()
- os.system(command)
os.system('cd /home/user/project/x')
os.system('date')
|