python讀寫檔案

2021-10-01 10:45:09 字數 1750 閱讀 4781

檔案讀寫過程

用shelve模組儲存變數

pprint.format()函式儲存變數

專案:生成

>>

>

import os

>>

> os.getcwd(

)'c:\\users\\administrator'

os.chdir更改目錄

>>

> os.chdir(

'c:\\windows\\addins'

)>>

> os.getcwd(

)'c:\\windows\\addins'

wait

>>

> os.makedirs(

'd:\\test'

)>>

> os.chdir(

'd:\\test'

)>>

> os.getcwd(

)'d:\\test'

使用os.path.join() 構建有效路徑

呼叫os.path.abspath(path) 將返回引數的絕對路徑的字串

>>

> os.path.abspath(

'.')

'd:\\test'

呼叫 os.path.isabs(path) 如果

>>

> os.path.getsize(

'e:\programmer\code\python\automatetheboringstuff\selenium\autoarrangementdocument\source\告警ip列表top20-1212.xlsx'

)12768

>>

> os.listdir(

'e:\programmer\code\python\automatetheboringstuff\selenium\autoarrangementdocument\source\\top20')[

'告警ip列表top20-1209.xlsx', '告警ip列表top20-1210.xlsx', '告警ip列表top20-1211.xlsx', '告警ip列表top20-1212.xlsx', '告警ip列表top20-1213.xlsx'

]

獲取目錄下所有檔案的總位元組數

import os

totalsize=

0path=

'e:\programmer\code\python\automatetheboringstuff\selenium\autoarrangementdocument\source\\top20'

for filename in os.listdir(path)

: totalsize=totalsize+os.path.getsize(os.path.join(path,filename)

)print

('總位元組數:'

,totalsize)

結果如下

c:\python37\python.exe e:/programmer/code/python/automatetheboringstuff/file/test/test1213.py

總位元組數: 61010

process finished with exit code 0

Python檔案讀寫

今天在看python檔案讀寫操作,發現python file name mode buffering file 函式用於建立乙個file物件,它有乙個別名叫open 可能更形象一些,它們是內建函式。來看看它的引數。它引數都是以字串的形式傳遞的。name是檔案的名字。mode 是開啟的模式,可選的值為...

python檔案讀寫

檔案讀寫模式 模式 描述 r以讀方式開啟檔案,可讀取檔案資訊。w以寫方式開啟檔案,可向檔案寫入資訊。如檔案存在,則清空該檔案,再寫入新內容 a以追加模式開啟檔案 即一開啟檔案,檔案指標自動移到檔案末尾 如果檔案不存在則建立 r 以讀寫方式開啟檔案,可對檔案進行讀和寫操作。w 消除檔案內容,然後以讀寫...

python 讀寫檔案

python讀寫檔案在文字不大的情況可以用正常的 open 然後讀入 readline行讀入 或者整體讀入 read readlines 基本知識 file open path,r 說明 第乙個引數是檔名稱,包括路徑 第二個引數是開啟的模式mode r 唯讀 預設。如果檔案不存在,則丟擲錯誤 w 只...