文件与目录操作
读文件
In [26]:
# 要以读文件的模式打开一个文件对象,使用Python内置的`open()`函数,传入文件名和标示符:
f = open('print_str.py', 'r')
# 如果文件打开成功,接下来,调用read()方法可以一次读取文件的全部内容,Python把内容读到内存,用一个str对象表示:
f.read()
# 最后一步是调用close()方法关闭文件。文件使用完毕后必须关闭,因为文件对象会占用操作系统的资源
f.close()
Out[26]:
'print("欢迎大家学习课程内容!")'
In [ ]:
# 异常处理模式
try:
f = open('/path/to/file', 'r')
print(f.read())
except Exception as e:
print e
finally:
if f:
f.close()
In [30]:
# 逐行读取
with open('test.py', 'r') as f:
for line in f.readlines():
print(line.strip())
for item in range(100):
print(item)
写文件
In [33]:
with open('test.txt', 'w') as f:
f