Table of Contents
1. 文件常见操作
Python提供了os、os.path、shutil等模块处理文件,其中包括打开文件、读写文件、复制和删除文件等函数。
1.2. 文件的创建
1.3. file类的常见操作
1.3.1 写取文件
context = "hello world!"
f = open("helloworld.txt", "w")
f.write(context)
f.close()
1.3.2 读取文件
context = "hello world!\n"
f = open("helloworld.txt", "a+")
f.write(context)
f.close()
count = 0
f = open("helloworld.txt", "r");
while True:
line = f.readline()
if (line):
print("line=%d, context=%s" % (count, line));
else:
break
count += 1
结果:
C:\Python\Python38\python.exe "E:/python/python project/hello world.py"
line=0, context=hello world!
line=1, context=hello world!
line=2, context=hello world!
1.4. os文件类操作
1.5. 文件内容的搜索、替换
使用正则表达式可以满足
1.6. 文件的比较
1.7. 配置文件ini的访问
2. 目录常见的操作
Python的os模块和os.path模块同样提供了一些针对目录操作的函数。
2.1 创建和删除
2.2 目录的遍历
2.2.1 递归
def VisitDir(path):
li = os.listdir(path)
for p in li:
pathname = os.path.join(path, p)
if not os.path.isfile(pathname):
VisitDir(pathname)
else:
print(pathname)
if __name__ == '__main__':
path = r"./"
VisitDir(path)
2.2.2 os.walk()
3. 文件和流
3.1 stdin
3.2 stdout
3.3. stderr