「作者主頁」:士別三日wyx
??此文章已錄入專欄《Python入門到精通》
??2021最新版Python小白教程,針對0基礎小白和基礎薄弱的伙伴學習
Python從入門到精通。 open() 函數用來打開文件
語法
open( name, mode )
參數
在 E 盤創建文件 a.txt ,使用 open() 函數打開該文件
file = open('E://a.txt')
print(file)
python的入門教程。輸出:
<_io.TextIOWrapper name='E://a.txt' mode='r' encoding='cp936'>
文件路徑分為兩種:
相對路徑是指「相對于當前文件」的路徑
打開當前目錄下的 a.txt 文件
file = open('a.txt')
print(file)
輸出:
<_io.TextIOWrapper name='a.txt' mode='r' encoding='cp936'>
python從入門到精通電子版,絕對路徑是指文章在「電腦」中的位置
打開 E 盤 Python 目錄下的 a.txt 文件
file = open('E://python/a.txt')
print(file)
輸出:
<_io.TextIOWrapper name='E://python/a.txt' mode='r' encoding='cp936'>
修改參數 mode 的值,可以指定文件的「打開方式」
Python打開,「打開模式」
file = open('a.txt', 'rt')
print(file)
輸出:
<_io.TextIOWrapper name='a.txt' mode='rt' encoding='cp936'>
在當前目錄創建文件 b.txt
open('b.txt', 'x')
檢查左側目錄,會多出一個文件 b.txt
Python處理文件? read() 函數用來讀取文件內容
語法
read( n )
參數
讀取文件 a.txt 的全部內容
file = open('a.txt', encoding='utf-8')
text = file.read()
print(text)
Python輸出到文件。輸出:
第一行
第二行
第三行
第四行
……
讀取文件 a.txt 的前 6個字符
file = open('a.txt', encoding='utf-8')
text = file.read(6)
print(text)
輸出:
第一行
第二
readline() 函數可以讀取一行內容
讀取文件 a.txt 第一行內容
file = open('a.txt', encoding='utf-8')
text = file.readline()
print(text)
python圖文教程、輸出:
第一行
file = open('a.txt', encoding='utf-8')
i = 0
while i < 3:text = file.readline()print(text)i += 1
輸出:
第一行第二行第三行
使用 for 循環遍歷文件,「逐行讀取」文件內容
file = open('a.txt', encoding='utf-8')
for text in file:print(text)
輸出:
第一行
第二行
第三行
第四行
……
close() 函數可以關閉文件,如果文件未關閉,對文件的「修改」可能會「不生效」
file = open('a.txt', encoding='utf-8')
print(file.read(3))
file.close()
輸出:
第一行
write() 函數可以向文件中寫入內容
修改文件內容時,需要指定 open() 函數的參數
向文件 a.txt 中追加內容
file = open('a.txt', 'a', encoding='utf-8')
file.write('新添加的內容')
file.close()# 修改模式的文件不可讀,需重新打開文件
file = open('a.txt', 'r', encoding='utf-8')
print(file.read())
輸出:
第一行新添加的內容
file = open('a.txt', 'w', encoding='utf-8')
file.write('新添加的內容')
file.close()# 修改模式的文件不可讀,需重新打開文件
file = open('a.txt', 'r', encoding='utf-8')
print(file.read())
輸出:
新添加的內容
exists() 函數可以判斷「文件是否存在」
remove() 函數可以根據文件名「刪除文件」
import osif os.path.exists('a.txt'):print('文件存在,刪除文件')os.remove('a.txt')
else:print('文件不存在,無法刪除')
輸出:
文件存在,刪除文件
rmdir() 函數可以刪除目錄(文件夾)
import osos.rmdir('mulu')
觀察左側目錄,文件夾 mulu 已被刪除
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态