欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python讀取和寫入txt、Excel文件和JSON文件的方法

 更新時間:2024年07月10日 09:22:18   作者:SiYuanFeng  
Python 提供了多種方法來讀取和寫入不同類型的文件,包括文本文件(txt)、Excel 文件和 JSON 文件,本文給大家介紹了一些常用的方法和示例代碼,對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下

Python 提供了多種方法來讀取和寫入不同類型的文件,包括文本文件(txt)、Excel 文件和 JSON 文件。以下是一些常用的方法和示例代碼:

讀取/寫入 txt 文件

基本讀取txt

讀取 txt 文件

  • 使用內(nèi)置的 open 函數(shù)
# 讀取整個文件內(nèi)容
with open('example.txt', 'r', encoding='utf-8') as file:
    content = file.read()
    print(content)

# 逐行讀取文件內(nèi)容
with open('example.txt', 'r', encoding='utf-8') as file:
    for line in file:
        print(line.strip())

寫入 txt 文件

  • 使用內(nèi)置的 open 函數(shù)
# 寫入文本到文件(覆蓋模式)
with open('example.txt', 'w', encoding='utf-8') as file:
    file.write('Hello, World!\n')

# 追加文本到文件
with open('example.txt', 'a', encoding='utf-8') as file:
    file.write('Appending a new line.\n')

按行讀取復(fù)雜數(shù)據(jù)

  • 逐行讀取并處理每行數(shù)據(jù)
# 假設(shè)我們的文件內(nèi)容如下:
# Name, Age, City
# Alice, 30, New York
# Bob, 25, Los Angeles

with open('example.txt', 'r', encoding='utf-8') as file:
    header = file.readline().strip().split(', ')
    data = []
    for line in file:
        values = line.strip().split(', ')
        record = dict(zip(header, values))
        data.append(record)
    print(data)

處理大txt文本文件(逐行讀取以節(jié)省內(nèi)存)

# 逐行讀取大文件
with open('large_file.txt', 'r', encoding='utf-8') as file:
    for line in file:
        process_line(line)  # 自定義的處理函數(shù)

讀取/寫入 Excel 文件

基本讀取

讀取 Excel 文件

  • 使用 pandas 庫
import pandas as pd

# 讀取 Excel 文件
df = pd.read_excel('example.xlsx', sheet_name='Sheet1')
print(df)
  • 使用 openpyxl 庫(適用于 .xlsx 文件)
from openpyxl import load_workbook

# 讀取 Excel 文件
wb = load_workbook('example.xlsx')
sheet = wb['Sheet1']
for row in sheet.iter_rows(values_only=True):
    print(row)

寫入 Excel 文件

  • 使用 pandas 庫
import pandas as pd

# 創(chuàng)建一個 DataFrame
data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]}
df = pd.DataFrame(data)

# 寫入 Excel 文件
df.to_excel('example.xlsx', sheet_name='Sheet1', index=False)
  • 使用 openpyxl 庫
from openpyxl import Workbook

# 創(chuàng)建一個新的 Excel 文件
wb = Workbook()
sheet = wb.active
sheet.title = 'Sheet1'

# 寫入數(shù)據(jù)
sheet.append(['Name', 'Age'])
sheet.append(['Alice', 25])
sheet.append(['Bob', 30])

# 保存文件
wb.save('example.xlsx')

處理復(fù)雜 Excel 文件(多個工作表)

  • 使用 pandas 讀取多個工作表
import pandas as pd

# 讀取 Excel 文件的所有工作表
xls = pd.ExcelFile('example.xlsx')
sheets = {}
for sheet_name in xls.sheet_names:
    sheets[sheet_name] = pd.read_excel(xls, sheet_name=sheet_name)
    print(f"Sheet: {sheet_name}")
    print(sheets[sheet_name])
  • 使用 openpyxl 逐行讀取
from openpyxl import load_workbook

# 讀取 Excel 文件
wb = load_workbook('example.xlsx')
for sheet_name in wb.sheetnames:
    sheet = wb[sheet_name]
    print(f"Sheet: {sheet_name}")
    for row in sheet.iter_rows(values_only=True):
        print(row)

處理大 Excel 文件(使用 pandas 的 chunksize 參數(shù))

import pandas as pd

# 逐塊讀取大 Excel 文件
chunk_size = 1000
for chunk in pd.read_excel('large_file.xlsx', sheet_name='Sheet1', chunksize=chunk_size):
    process_chunk(chunk)  # 自定義的處理函數(shù)

讀取/寫入 JSON 文件

基本讀取

基本讀取 JSON 文件

  • 使用內(nèi)置的 json 模塊
import json

# 讀取 JSON 文件
with open('example.json', 'r', encoding='utf-8') as file:
    data = json.load(file)
    print(data)

寫入 JSON 文件

  • 使用內(nèi)置的 json 模塊
import json

# 數(shù)據(jù)
data = {'name': 'Alice', 'age': 25}

# 寫入 JSON 文件
with open('example.json', 'w', encoding='utf-8') as file:
    json.dump(data, file, ensure_ascii=False, indent=4)

讀取嵌套數(shù)據(jù):

讀取嵌套json文件:

  • 讀取嵌套 JSON 數(shù)據(jù)
import json

# 假設(shè)我們的 JSON 文件內(nèi)容如下:
# {
#     "name": "Alice",
#     "age": 30,
#     "address": {
#         "city": "New York",
#         "zipcode": "10001"
#     },
#     "phones": ["123-456-7890", "987-654-3210"]
# }

with open('example.json', 'r', encoding='utf-8') as file:
    data = json.load(file)
    print(data)

# 訪問嵌套數(shù)據(jù)
print(data['address']['city'])  # 輸出: New York
print(data['phones'][0])  # 輸出: 123-456-7890

寫入嵌套 JSON 數(shù)據(jù)

import json

# 嵌套數(shù)據(jù)
data = {
    "name": "Alice",
    "age": 30,
    "address": {
        "city": "New York",
        "zipcode": "10001"
    },
    "phones": ["123-456-7890", "987-654-3210"]
}

# 寫入 JSON 文件
with open('example.json', 'w', encoding='utf-8') as file:
    json.dump(data, file, ensure_ascii=False, indent=4)

復(fù)雜讀取json文件

按行讀取 JSON 文件在處理大文件或流式處理數(shù)據(jù)時非常有用。以下是一些方法來按行讀取 JSON 文件:

方法一:逐行讀取并解析每行 JSON

如果 JSON 文件每行都是一個獨立的 JSON 對象,可以逐行讀取并解析每行:

import json

# 假設(shè)我們的 JSON 文件內(nèi)容如下,每行是一個獨立的 JSON 對象:
# {"name": "Alice", "age": 30}
# {"name": "Bob", "age": 25}

with open('example.json', 'r', encoding='utf-8') as file:
    for line in file:
        data = json.loads(line.strip())
        print(data)

方法二:逐行讀取并解析嵌套 JSON

如果 JSON 文件是一個包含多個對象的數(shù)組,可以使用 ijson 庫逐行解析嵌套 JSON 數(shù)據(jù):

import ijson

# 假設(shè)我們的 JSON 文件內(nèi)容如下:
# [
#     {"name": "Alice", "age": 30},
#     {"name": "Bob", "age": 25}
# ]

with open('example.json', 'r', encoding='utf-8') as file:
    parser = ijson.parse(file)
    for prefix, event, value in parser:
        if prefix.endswith('.name') and event == 'string':
            print(f"Name: {value}")
        elif prefix.endswith('.age') and event == 'number':
            print(f"Age: {value}")

方法三:處理大 JSON 文件(分塊讀取)

對于非常大的 JSON 文件,可以考慮分塊讀取和處理:

import json

def process_chunk(chunk):
    for line in chunk:
        data = json.loads(line.strip())
        print(data)

chunk_size = 1000  # 每次讀取1000行

with open('large_file.json', 'r', encoding='utf-8') as file:
    chunk = []
    for line in file:
        chunk.append(line)
        if len(chunk) >= chunk_size:
            process_chunk(chunk)
            chunk = []
    if chunk:
        process_chunk(chunk)

方法四:使用 jsonlines 庫

jsonlines 庫專門用于處理每行一個 JSON 對象的文件:

import jsonlines

# 假設(shè)我們的 JSON 文件內(nèi)容如下,每行是一個獨立的 JSON 對象:
# {"name": "Alice", "age": 30}
# {"name": "Bob", "age": 25}

with jsonlines.open('example.json') as reader:
    for obj in reader:
        print(obj)

這些方法可以幫助你按行讀取 JSON 文件,根據(jù)文件的具體結(jié)構(gòu)和大小選擇合適的方法來處理數(shù)據(jù)。
以上是一些常見的方法來讀取和寫入 txt、Excel 和 JSON 文件。每種方法都有其優(yōu)缺點,選擇哪種方法取決于具體的需求和使用場景。

以上就是Python讀取和寫入txt、Excel文件和JSON文件的方法的詳細(xì)內(nèi)容,更多關(guān)于Python讀取和寫入txt、Excel和JSON的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 詳解python中的文件與目錄操作

    詳解python中的文件與目錄操作

    這篇文章主要介紹了詳解python中的文件與目錄操作的相關(guān)資料,需要的朋友可以參考下
    2017-07-07
  • 使用keras實現(xiàn)孿生網(wǎng)絡(luò)中的權(quán)值共享教程

    使用keras實現(xiàn)孿生網(wǎng)絡(luò)中的權(quán)值共享教程

    這篇文章主要介紹了使用keras實現(xiàn)孿生網(wǎng)絡(luò)中的權(quán)值共享教程,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-06-06
  • Python實現(xiàn)根據(jù)Excel表格某一列內(nèi)容與數(shù)據(jù)庫進(jìn)行匹配

    Python實現(xiàn)根據(jù)Excel表格某一列內(nèi)容與數(shù)據(jù)庫進(jìn)行匹配

    這篇文章主要為大家詳細(xì)介紹了Python如何使用pandas庫和Brightway2庫實現(xiàn)根據(jù)Excel表格某一列內(nèi)容與數(shù)據(jù)庫進(jìn)行匹配,需要的可以參考下
    2025-02-02
  • 懶人必備Python代碼之自動發(fā)送郵件

    懶人必備Python代碼之自動發(fā)送郵件

    在傳統(tǒng)的工作中,發(fā)送會議紀(jì)要是一個比較繁瑣的任務(wù),需要手動輸入郵件內(nèi)容、收件人、抄送人等信息,每次發(fā)送都需要重復(fù)操作,不僅費時費力,而且容易出現(xiàn)疏漏和錯誤。本文就來用Python代碼實現(xiàn)這一功能吧
    2023-05-05
  • Python3標(biāo)準(zhǔn)庫之dbm UNIX鍵-值數(shù)據(jù)庫問題

    Python3標(biāo)準(zhǔn)庫之dbm UNIX鍵-值數(shù)據(jù)庫問題

    dbm是面向DBM數(shù)據(jù)庫的一個前端,DBM數(shù)據(jù)庫使用簡單的字符串值作為鍵來訪問包含字符串的記錄。這篇文章主要介紹了Python3標(biāo)準(zhǔn)庫:dbm UNIX鍵-值數(shù)據(jù)庫的相關(guān)知識,需要的朋友可以參考下
    2020-03-03
  • python實現(xiàn)多層感知器

    python實現(xiàn)多層感知器

    這篇文章主要為大家詳細(xì)介紹了python實現(xiàn)多層感知器的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-01-01
  • Pytorch搭建SRGAN平臺提升圖片超分辨率

    Pytorch搭建SRGAN平臺提升圖片超分辨率

    這篇文章主要為大家介紹了Pytorch搭建SRGAN平臺提升圖片超分辨率,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-04-04
  • 基于pandas向csv添加新的行和列

    基于pandas向csv添加新的行和列

    這篇文章主要介紹了基于pandas向csv添加新的行和列,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-05-05
  • Python結(jié)合spaCy?進(jìn)行簡易自然語言處理

    Python結(jié)合spaCy?進(jìn)行簡易自然語言處理

    這篇文章主要為大家介紹了Python結(jié)合spaCy進(jìn)行簡易自然語言處理詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-06-06
  • 使用Python結(jié)合Tkinter和PyAutoGUI開發(fā)精確截圖工具

    使用Python結(jié)合Tkinter和PyAutoGUI開發(fā)精確截圖工具

    在日常工作中,截圖是一個非常常見的需求,雖然?Windows?自帶截圖工具,但有時我們需要更精確的截圖方式,比如選取特定區(qū)域、快速保存截圖并進(jìn)行預(yù)覽,本篇博客將介紹一個使用?Python?結(jié)合?Tkinter?和?PyAutoGUI?開發(fā)的精確截圖工具,需要的朋友可以參考下
    2025-03-03

最新評論