文件(txt/json/csv)读写

文件(txt/json/csv)读写

写入csv

import csv
withopen( 'some.csv', 'w', encoding="UTF-8", newline= '') as f:
		writer = csv.writer(f)
    # writer.writerow(), 将多列数据写入一行
    writer.writerow([ "123", "234", "345"])
    writer.writerow([ "abc", "efg", "hij"])
    # writer.writerows(),  将一个二维列表中的每一个列表写为一行。
    writer.writerows([[1, 2],[3, 4],[4, 5]])
'''
writer.writerows() 结果如下:
[[1, 2],
 [3, 4],
 [4, 5]]
'''

读写txt

# with方式可以避免没有关闭资源文件产生错误
# 读
# read(),一次读取全部内容到[内存](https://so.csdn.net/so/search?q=内存&spm=1001.2101.3001.7020)。
with open('file.txt', 'r') as f:
    print(f.read()) 

# 2、readlines(),with方式,逐行读取。
with open("file.txt", 'r') as lines:
    for line in lines:
        print(line)

#写
with open("file.txt", 'w') as f:
    f.write('测试')
    

# 其他方法 open()
# 打开文件
f = open("file.txt", "r")
print ("文件名为: ", f.name)
for line in fo.readlines():       #依次读取每行  
    line = line.strip()           #去掉每行头尾空白  
    print ("读取的数据为: %s" % (line))

# 关闭文件
f.close()

json

https://blog.csdn.net/qq_41422774/article/details/97394651

# 1
with open('抽取输出1.json', 'w') as file_obj:
		json.dump(results, file_obj, ensure_ascii=False)
# 2
with open("index2request_data.json", "w") as f:
     f.write(json.dumps(index2request_data, ensure_ascii=False, indent=4, separators=(',', ':')))

# 字典转码
res = json.loads(json.dumps(res, ensure_ascii=False))
# 读取json文件
with open("index2request_data.json", "w") as f:
     res = json.loads(f.read())
# 不推荐
res = json.loads(open('ner.json', 'r').read())
  1. Python 3已经将unicode作为默认编码
  2. Python 3中的json在做dumps操作时,会将中文转换成unicode编码,并以16进制方式存储,再做逆向操作时,会将unicode编码转换回中文, 但在做逆向操作load和loads时会转换为中文,但是中间态(例如存储的json文件)的中文编码方式仍然是unicode
  3. 这就解释了,为什么json.dumps操作后,得到的字符串是\uXXXX。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AosisDevDoHub

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值