How to save data to file in Python

IO (Input/Output) refers to the data exchange between the computer and the external environment. IO operations in Python are divided into file IO and network IO.

File IO: Python provides a built-in file object to implement file IO operations. File objects are created by the built-in open() function, which can be used to read, write, and modify files.

Network IO: Python supports network IO operations through the socket module. Using the socket module, you can create TCP/UDP sockets for network communication.

Many advanced IO libraries are also provided in Python, such as: io, pickle, json, etc., which can conveniently serialize and deserialize data. In addition, Python also supports standard input and output (stdin/stdout), which can interact with the operating system and realize command line input and output operations.

Method 1: open function

The open function is one of the built-in functions of Python, which is used to open a file and return a file object, which can be used to read or write files. Its usual syntax is:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Parameter analysis:
file indicates the name of the file to be opened (including the path),
mode indicates the mode of opening the file, and the default is read-only mode ('r'). For the write mode, you can use 'w', 'x', 'a', etc., which respectively represent overwriting, creating a new file and writing, adding content at the end of the file, etc.
buffering indicates the buffering strategy, the default is to use the system's default buffering mechanism,
encoding indicates the file encoding method, and
errors indicates the processing method when the encoding error occurs.
newline indicates the conversion strategy for newline characters,
closefd indicates whether to close the file descriptor at the same time when the file is closed, and
opener indicates the way to customize the file opening.

#使用with open()新建对象f
with open('file.txt','w',encoding='utf-8') as f:
    for i in comments:
        #写入数据,文件保存在上面指定的目录,加\n为了换行更方便阅读  
        f.write(i+'\n')

Method 2: numpy

NumPy is one of the most important modules in Python scientific computing. It provides a very flexible array object for convenient manipulation of numerical data. NumPy also provides efficient matrix operations, fast Fourier transforms, and more.

# 导入NumPy模块
import numpy as np

# 创建NumPy数组对象并填充数据
arr = np.array([[1, 2, 3], [4, 5, 6]])

# 调用NumPy提供的savetxt()函数将数组数据写入文件中
np.savetxt('output.txt', arr)
# savetxt()函数有很多可选参数来控制格式、精度等选项。例如,可以使用delimiter参数设置分隔符,使用fmt参数设置输出格式
np.savetxt('output.txt', arr, delimiter=',', fmt='%d')

Method 3: csv

Python's csv module is a standard library for reading and writing CSV (Comma-Separated Values) format files. The CSV format is often used for the storage and exchange of large amounts of data, such as computer data, tabular data, statistical data, and so on.

import csv

# 打开文件
with open('data.csv', 'w', newline='') as file:
    # 创建writer对象
    writer = csv.writer(file)
    
    # 写入一行数据
    writer.writerow(['姓名', '年龄', '性别'])
    
    # 写入多行数据
    rows = [
        ['张三', 20, '男'],
        ['李四', 22, '女'],
        ['王五', 18, '男'],
    ]
    writer.writerows(rows)

Method 4: DataFrame

pandas is a Python library for data analysis, the main data structure of which is DataFrame. The DataFrame class provides multiple methods for writing data to files, to_csv()writing DataFrame to CSV file, to_excel()DataFrame to Excel file, and to_json()methods to convert DataFrame to JSON format data. These methods provide multiple parameters for use. For example, control output format, data type, missing value processing, etc., see pandas official documentation for details.

to_csv() method: write DataFrame to CSV file

import pandas as pd

# 创建一个DataFrame
data = {
    
    'name':['Tom', 'Jack', 'Steve', 'Ricky'], 'age':[28, 34, 29, 42]}
df = pd.DataFrame(data)

# 将DataFrame写入CSV文件
df.to_csv('output.csv', index=False)

to_excel() method: write DataFrame to Excel file

import pandas as pd

# 创建一个DataFrame
data = {
    
    'name':['Tom', 'Jack', 'Steve', 'Ricky'], 'age':[28, 34, 29, 42]}
df = pd.DataFrame(data)

# 将DataFrame写入Excel文件
df.to_excel('output.xlsx', index=False)

Method five: codecs

The codecs module in Python provides some encoding and decoding functions, which can help us deal with different character sets when reading and writing files. The codecs module also provides many other functions, such as open(), encode(), decode(), lookup(), etc., which can be used to deal with various common encoding methods, such as UTF-8, ASCII, etc.

import codecs #或者io,使用哪种包无所谓

# 代码使用`codecs.open()`函数打开文件,第一个参数是文件路径,第二个参数指定文件打开模式,`w`表示写入,`r`表示读取。第三个参数是指定文件编码,这里是UTF-8编码。
with codecs.open('your_file.txt', 'r', 'utf-8') as f:
    f.write('This method is prior')

Guess you like

Origin blog.csdn.net/weixin_44008788/article/details/125074069