Python学习记录(四):文件读写

一、Python读写txt文件

1.1 python读取txt文件

in_text_file = "xxx.txt"

with open(in_text_file) as f:
  lines = f.readlines()
  lines = [line.strip() for line in lines]

print(lines)

1.2 python写入txt文件

out_text_file = "yyy.txt"

with open(out_text_file, 'w') as f:
  print("writing to text file", file=f)

Append a file: https://stackoverflow.com/questions/4706499/how-do-i-append-to-a-file

二、Python读写json文件

使用Python内置包json进行Json文件的读写,相关API包括:

  • json.load()
  • json.dumps()json.dump()

2.1 读json

import json

# Opening JSON file
with open('example.json', 'r') as openfile:

	# Reading from json file
	json_object = json.load(openfile)

print(json_object)
print(type(json_object))

2.2 写Json

json.dumps()首先将Python Object转为Json Object,然后再写入Json文件,Json文件可用VS Code打开

参考链接:https://www.geeksforgeeks.org/reading-and-writing-json-to-a-file-in-python/

三、Python读写csv文件

3.1 读csv

https://www.geeksforgeeks.org/reading-csv-files-in-python/

3.2 写csv

Ref. https://www.geeksforgeeks.org/writing-csv-files-in-python/
csvwriter只有writerow方法,没有writecol。原因应该是逗号分隔是行内分隔。

四、Python读写Excel文件

首先安装pip install xlsxWriter

五、Python读取MATLAB mat文件

https://towardsdatascience.com/how-to-load-matlab-mat-files-in-python-1f200e1287b5

from scipy.io import loadmat
annots = loadmat('cars_train_annos.mat')

print(annots.keys())

六、ipynb文件转python

Ref. https://linuxhint.com/convert-jupyter-notebook-python/

pip install jupyter
jupyter nbconvert xxx.ipynb --to python

Update: 可以用VSCode打开ipynb文件

posted @ 2022-09-03 15:22  达可奈特  阅读(128)  评论(0编辑  收藏  举报