Python文件操作

# python 学习之文件和异常

print("python 文件和异常")

# 打开文件
# with关键字指定python自动处理文件打开和关闭,并且文件对象只有在with代码块里面才有效
with open("file.txt") as file: 
    text = file.read()  # read()方法读取文本中所有内容
    print(text.strip())

# 逐行读取
with open("file.txt") as file:
    row = 0
    for line in file:
        row += 1
        print(str(row) + ": " + line, end="")
print("")

# 返回由文件各行组成的列表
with open("file.txt") as file:
    lines = file.readlines()
for line in lines:
    print(line, end="")
print("")

# 写文件
with open("write.txt", "w") as file:  # open()函数附加参数 w-写  r-读  a-附加  r+-读和写
    file.write("Hello World, Python!!!\n") #write()函数在文本后面添加字符串
    file.write("Hello World, C!!!")
with open("write.txt") as file:
    print(file.read())

# JSON文件的操作
import json
number = [2,3,5,7,11,13]
filename = "number.json"
with open(filename, 'w') as f_json:
    json.dump(number, f_json) # dump()函数两个参数分别为存储数据以及可用的json文件对象
with open(filename) as f_json:
    print(json.load(f_json))  # load()函数加载存储在json文件中的信息

 

posted @ 2018-09-24 22:51  前端人生  阅读(205)  评论(0编辑  收藏  举报