#!/usr/bin/python3f = open("/Users/haha/Desktop/haha.txt", "w")f.write("hahahahanhehehehehn" )# 关闭打开的文件f.close()
结果:写到了文件中
15.2 文件读取 15.2.1 普通读取#!usr/bin/python3f = open("/Users/haha/Desktop/haha.txt", "r")str = f.read()print(str)f.close()
结果:
haha10
hehe10
#!usr/bin/python3f = open("/Users/haha/Desktop/haha.txt", "r")str = f.readline()print(str)f.close()
结果:
haha10
15.2.2.2 一次读取所有行#!usr/bin/python3f = open("/Users/haha/Desktop/haha.txt", "r")str = f.readlines()print("str10 = ", str)f.close()
结果:
str10 = ['haha10n', 'hehe10n']
15.2.3 迭代一个文件对象然后读取每行#!usr/bin/python3f = open("/Users/haha/Desktop/haha.txt", "r")for line in f: print(line)f.close()
结果:
haha10
hehe10
15.3 os 15.3.1 相关函数 15.3.1.1 os.getcwd()返回当前工作目录
#!usr/bin/python3import osprint(os.getcwd())
结果:
/Users/haha/source/builder/builder/handler
15.3.1.2 listdir()返回指定路径下的文件和文件夹列表
#!/usr/bin/python3import ospath = "/Users/haha/Desktop"dirs = os.listdir(path)for file in dirs: print(file)
结果:
展示出path路径下的的所有其他文件或文件夹
15.4 with关键字使用 with 关键字系统会自动调用 f.close() 方法, with 的作用等效于 try/finally 语句是一样的
#!usr/bin/python3with open("/Users/bytedance/Desktop/haha.txt", 'r') as file: str = file.read() print("str = ", str)
结果:
str = haha10
hehe10