首页 > 编程语言 > 详细

Python文件操作

时间:2018-09-25 00:03:06      阅读:152      评论:0      收藏:0      [点我收藏+]
# 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文件中的信息

 

Python文件操作

原文:https://www.cnblogs.com/BlogsOfLei/p/9697169.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!