溫馨提示×

python讀取文本文件并輸出的方法是什么

小億
183
2023-08-15 10:28:30
欄目: 編程語言

Python中讀取文本文件并輸出的方法有多種,可以根據具體需求選擇合適的方法。

  1. 使用open()函數和read()方法:
file = open("file.txt", "r")  # 打開文件
content = file.read()  # 讀取文件內容
print(content)  # 輸出文件內容
file.close()  # 關閉文件
  1. 使用with語句和read()方法:
with open("file.txt", "r") as file:  # 打開文件
content = file.read()  # 讀取文件內容
print(content)  # 輸出文件內容
  1. 逐行讀取并輸出文件內容:
with open("file.txt", "r") as file:  # 打開文件
for line in file:  # 逐行讀取文件內容
print(line)  # 輸出每一行內容
  1. 讀取文件內容并按行存儲為列表,然后輸出:
with open("file.txt", "r") as file:  # 打開文件
lines = file.readlines()  # 讀取文件內容,并按行存儲為列表
for line in lines:  # 遍歷每一行內容
print(line)  # 輸出每一行內容

這些方法都可以實現讀取文本文件并輸出其內容。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女