Python实例

读写文件

写文件

#!/usr/bin/env python3

with open('test.txt', 'w') as f:
    f.write('hello\n')
    f.write('python')

读文件

#!/usr/bin/env python3

with open('test.txt', 'r') as f:
    for l in f.readlines():
        print(l, end='')

遍历文件夹下的所有文件

#!/usr/bin/env python3

import pathlib
import pprint

pprint.pprint(list(pathlib.Path().rglob("*")))

遍历所有文件,gbk转码为utf-8

#!/usr/bin/env python3

import pathlib

for path in pathlib.Path().rglob("*"):
    file_name = str(path.resolve())
    if not file_name.endswith(".h") or not file_name.endswith("*.cpp"):
        continue

    f1 = open(file_name, "rb")
    content = str(f1.read(), "gbk")
    f1.close()

    f2 = open(file_name, "wb")
    f2.write(content.encode("utf8"))
    f2.close()
    print(file_name)