# Basic use of Python csv, xlsx, json, binary (MP3) file reading and writing

Basic use of Python csv, xlsx, json, binary (MP3) file reading and writing



foreword


提示:以下是本篇文章正文内容,下面案例可供参考

1. What is file reading and writing?

"Flow" is an abstract concept and a metaphor. The flow of water flows from one end to the other, and the "flow" in python is data, and the data will "flow" from one end to the other, according to the direction of the flow We can divide the stream into input stream and output stream. When the program needs to read data from the data source, it will open an input stream. On the contrary, writing data will also open an output stream, and the data to be written will be opened. The source can be a file, memory or network, etc.

Second, the file read and write method

read mode describe
r Read-only (default), the file needs to exist;
r+ Can be read or written, the file needs to exist;
rb Indicates that the file is read in binary mode, and the file must exist;
in Write only, open a new file for writing, overwrite if the file exists;
in + Can be read or written, open to create a new file and write data, if the file already exists, it will be overwritten;
wb Binary write, open a new file for writing, overwrite if the file exists;
a For additional writing, the file must exist, and continue to write new content at the end of the file content;
a+ Append writing, if the file does not exist, a new file will be created, and the new content will continue to be written at the end of the file content;

Three, csv file read and write

1. Introduction to csv

CSV files usually use commas to separate each specific data value (also ': ::', '; ;;', etc.), and the specific file structure is as follows:

2. csv write

file_path = "number.csv"
content_list = ['1,2,3,4,5\n', '6,7,8,9,10\n', '11,12,13,14,15\n', '16,17,18,19,20\n']
with open(file=file_path, mode='w', encoding='utf-8') as fis:
    for content in content_list:
        fis.write(content)
        print(f"写入成功:{content}", end='')

console print
csv file content

3. csv read in

file_path = "number.csv"
with open(file=file_path, mode='r', encoding='utf-8') as fis:
    content_list = fis.readlines()
for content in content_list:
    print(f"读入成功:{content}", end='')
    print(content.strip())

console print

Fourth, XLSX file read and write

1. Introduction to xlsx

xlsx is an extension for Microsoft Office EXCEL 2007/2010/2013/2016/2019 documents. Its compressed file format based on the Office Open XML standard replaces its previously proprietary default file format with the addition of the letter "x" to the traditional filename extension (i.e. ".docx" instead of ".doc", ".xlsx" " replaces ".xls", ".pptx" replaces ".ppt"). Any word processing software that can open a ".xlsx" file can convert the document to a ".xls" file, which takes up less space than a ".xls" file

2.xlsx write

import pandas as pd
file_path = 'number.xlsx'
data_list = pd.DataFrame(columns=('A', 'B', 'C', 'D', 'E'))  # pandas Version: 1.1.3
content_list = [['1', '2', '3', '4', '5\n'], ['6', '7', '8', '9', '10\n'], ['11', '12', '13', '14', '15\n']]
for ls in content_list:
    result_list = data_list.append(pd.DataFrame(
        {
    
    
            'A': [ls[0]], 'B': [ls[1]], 'C': [ls[2]], 'D': [ls[3]], 'E': [ls[4]]
        }
    ))
    print(f"存入成功:{ls}")
with pd.ExcelWriter(file_path, engine="openpyxl", mode='a+') as writer:  # openpyxl Version: 3.0.10
    data_list.to_excel(writer, sheet_name='sheet1', index=False)
print("数据写入成功!")

console print
insert image description here

3.xlsx read in

import pandas as pd
file_path = 'number.xlsx'
df = pd.read_excel(io=file_path, sheet_name=0)
a_list = list(df['A'])  # 按列提取,根据列名,得到list
print('a_list:', a_list)
for index, row in df.iterrows():  # index = 行标号(索引)
    print(row)  # 按行遍历
    print(f"row['A']: {row['A']}")  # 根据列名在当前行提取值
    break

console output
注意报错信息:ImportError: Missing optional dependency 'xlrd'. Install xlrd >= 1.0.0 for Excel support Use pip or conda to install xlrd.
Need to install the library: pip install xlrd==1.2.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
pandas Common method: https://www.lmlphp.com/user/60946/article/item /2367333/

Five, JSON file read and write

1. Introduction to json

JSON (JavaScript Object Notation, JS Object Notation) is a lightweight data exchange format. It is based on a subset of ECMAScript (the js specification developed by the European Computer Manufacturers Association), and uses a text format that is completely independent of the programming language to store and represent data. Concise and clear hierarchy makes JSON an ideal data exchange language. It is easy for humans to read and write, but also easy for machines to parse and generate, and effectively improve the efficiency of network transmission.

2.json write

import json
from pprint import pprint
file_path = 'number.json'
content_list = [['1', '2', '3', '4', '5'], ['6', '7', '8', '9', '10'], ['11', '12', '13', '14', '15']]
key_list = ['A', 'B', 'C']
data = dict()
for i in range(len(content_list)):
    data[key_list[i]] = content_list[i]
with open(file=file_path, mode='w', encoding='utf-8') as fis:
    fis.write(json.dumps(obj=data, ensure_ascii=False, indent=4))
pprint(data)
print("json数据写入完成")

console print
json file content

3.json read

import json
from pprint import pprint
file_path = 'number.json'
with open(file=file_path, mode='r', encoding='utf-8') as fis:
    content = fis.read()
json_data = json.loads(content)  # 序列化之后可以根据字典方式存取数据
json_data['D'] = ['16', '17', '18', '19', '20']
pprint(json_data)

console output

6. Binary (MP3) writing

1. Introduction to Binary

Binary, discovered by Leibniz, is a base-2 numbering system in mathematical and digital circuits, and a binary system that represents the system with base 2. In this system, two different symbols 0 (representing zero) and 1 (representing one) are usually used to represent [1]. In digital electronic circuits, the implementation of logic gates directly applies binary, which is used in modern computers and computer-dependent devices. Each digit is called a bit (Bit, short for Binary digit)

2. Binary (MP3) writing

import requests
file_path = 'test.mp3'
headers = {
    
    
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36'
}
url = 'https://m701.music.126.net/20221023111433/7c8defd5c895b331c9df055e99619652/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/7385120648/b9ed/2e3d/169a/941c017bebc80041b787542396dab922.m4a'
response = requests.get(url=url, headers=headers)
with open(file_path, 'wb') as fis:
    for chunk in response.iter_content(chunk_size=1000):
        fis.write(chunk)
        fis.flush()
print("歌曲下载完成!")

download file mp3
start listening

3. Binary (MP3) read in

file_path = 'test.mp3'
with open(file_path, 'rb') as fis:
    content = fis.read()

Summarize

For example: the above is what I will talk about today. This article only briefly introduces the read and write use of files, and the follow-up common read operations will continue to be updated in this blog;

おすすめ

転載: blog.csdn.net/EXIxiaozhou/article/details/127466308