import os
# __file__ 表示当前文件路径
print(__file__)
# os.getcwd() 表示当前的工作目录
print(os.getcwd())
#桌面路径
#1. 在当前文件目录下新建文件夹 pyTest,用__file__绝对路径也可以
if not os.path.exists('./pyTest'):
os.mkdir("./pyTest")
#2. 改变当前目录
os.chdir(os.getcwd() + '\\pyTest')
print(os.getcwd())
#3. 在pyTest中新建文件 1.txt
fileObj = open('./1.txt', 'a+')
for i in range(100):
fileObj.write(str(i) + '\n')
fileObj.flush()
fileObj.close()
#4. 读取1.txt
fileObj = open('./1.txt', 'r')
# readline() 方式读取
# while True:
# lineStr = fileObj.readline()
# if lineStr:
# print(lineStr, end='')
# else:
# break
# next() 方式读取
#try:
# while True:
# lineStr = next(fileObj)
# if lineStr:
# print(lineStr, end='')
# else:
# break
#except Exception as e:
# pass
# iter 迭代器方式读取 推荐使用
#iter = iter(fileObj)
#for line in iter:
# print(line, end='')
# 感觉和上面的迭代器没啥区别
iter = iter(fileObj)
try:
while True:
line = next(iter)
if line:
print(line, end='')
else:
break
except Exception as e:
pass
fileObj.close()
os.chdir('../')
print(os.getcwd())
# 删除非空文件夹
shutil.rmtree('pyTest')