python中文件的讀取與寫入以及os模塊

1.文件讀取的三部曲:打開 ---> 操作 ----> 關閉

r(默認參數):
-只能讀,不能寫
-讀取文件不存在 會報錯
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/westos'

w(寫)
-write only
-文件不存在的時候,會自動創建新的文件
-文件存在的時候,會清空文件內容並寫入新的內容

a(追加):
-write only
-寫:不會清空文件的內容,會在文件末尾追加
-寫:文件不存在,不會報錯,會創建新的文件並寫入內容
r+
-r/w
-文件不存在,報錯
-默認情況下,從文件指針所在位置開始寫入

w+
-r/w
-文件不存在,不報錯
-會清空文件內容

a+
-r/w
-文件不存在,不報錯
-不會清空文件,在末尾追加   

f = open('/tmp/westos3','w+') /tmp/westos3文件不存在,自動創建了文件並寫入了信息

print(f)
print(f.tell()) 打印文件指針的位置 此時爲0
f.write('111') 寫入‘111’
print(f.tell()) 再次打印指針位置可以看到指針爲3
f.close() 關閉文件

python中文件的讀取與寫入以及os模塊

f = open('/tmp/redhat','a+') 不會清空文件,在末尾追加
print(f) 文件指針的位置開始爲0
print(f.tell())
f.write('111') 文件執行5此後指針在15
print(f.tell())
f.close() 關閉文件

python中文件的讀取與寫入以及os模塊python中文件的讀取與寫入以及os模塊

2.文件的操作

#1.打開文件
f = open('/tmp/westos','r')
#2.操作
print(f)
#讀文件
#content = f.read()
#print(content)

#寫文件
#告訴當前的文件指針所在的位置
#print(f.tell())
#f.write('westos')
#print(f.tell())
#f.write('redhat')
#print(f.tell())

#判斷文件對象擁有的權限
print(f.readable()) 是否可讀
print(f.writable()) 是否可寫
print(f.tell()) 文件的指針
content = f.read() 把讀取的內容指向content
print(content)
print(f.tell())
content1 = f.read()
print(content1)
#print(content)

3.關閉文件
f.close()

2.如果讀取是 圖片 音頻 視頻(非純文本文件)
需要通過二進制的方式讀取和寫入
-讀取純文本
r r+ w w+ a a+ == rt rt+ wt wt+ at at+
-讀取二進制文件
rb rb+ wb wb+ ab ab+

#讀取二進制文件內容
f1 = open('hello.png',mode='rb') 只讀模式
content = f1.read()
f1.close()

#寫入要複製的文件的內容
f2 = open('lucky.jpg',mode='wb') 寫入模式
f2.write(content)
f2.close()

複製hello.png並創建新的lucky.jpg
python中文件的讀取與寫入以及os模塊

3.
默認情況下讀取文件的內容 小的文件:直接用read讀取即可
如果是一個大文件(文件大小>=內存大小) readline()
f = open('/tmp/passwd','rb+')
#按行讀取
#print(f.readline())

#按字節讀取
#print(f.read(3))
#讀取文件內容,並返回一個列表,列表元素分別爲文件的行內容
print(f.readlines())
#指針的移動
#print(f.tell())
#print(f.read(10))
#print(f.tell())
#f.seek(2,2)

seek:指針移動
第一個參數:偏移量 >0:代表向後移動 <0 代表向前移動
第二個參數:
0:移動指針到文件開頭
1:當前位置
2:移動指針到末尾

python中文件的讀取與寫入以及os模塊

#讀取/tmp/passwd內容,返回一個列表,去掉後面的\n

f = open('/tmp/passwd')
print(list(map(lambda x:x.strip(),f.readlines())))
print([line.strip() for line in f.readlines()])
f.close()

#創建文件data.txt 文件共100000行,
#每行存放以一個1~100之間的整數

import random

f = open('data.txt','a+')
for i in range(100000):
f.write(str(random.randint(1,100)) + '\n')
#移動文件指針
f.seek(0,0)
print(f.read())
f.close()

python中文件的讀取與寫入以及os模塊python中文件的讀取與寫入以及os模塊

4.
上下文管理器:打開文件,執行完with語句內容之後,自動關閉文件
with open('/tmp/passwd') as f:
print(f.read())
python中文件的讀取與寫入以及os模塊
#將第一個文件的內容寫道第二個文件中
with open('date.txt') as f1,open('data3.txt','w+') as f2:
f2.write(f1.read())
f2.seek(0,0)
print(f2.read())
python中文件的讀取與寫入以及os模塊

練習:
生成100個MAC地址並寫入文件中,MAC地址前6位(16進制)爲01-AF-3B

01-AF-3B-xx-xx-xx
-xx
01-AF-3B-xx
-xx
01-AF-3B-xx-xx
-xx
01-AF-3B-xx-xx-xx

import string
import random

def create_mac():
MAC = '01-AF-3B'
#生成16進制的數
hex_num = string.hexdigits
for i in range(3):

從16進制字符串中隨即選出兩個數字來

    #返回值是列表
    n = random.sample(hex_num, 2)
    #拼接列表中的內容,將小寫的字母轉換成大寫的字母
    sn = '-' + ''.join(n).upper()
    MAC += sn
return MAC

#主函數:隨即生成100個MAC地址
def main():

以寫的方式打開一個文件

with open('mac.txt', 'w') as f:
    for i in range(100):
        mac = create_mac()
        print(mac)
        #每生成一個MAC地址,存入文件
        f.write(mac + '\n')

main()

python中文件的讀取與寫入以及os模塊

#1. 生成一個大文件ips.txt,要求1200行,每行隨機爲172.25.254.0/24段的ip;
#2. 讀取ips.txt文件統計這個文件中ip出現頻率排前10的ip;

import random

def create_ip_file(filename):
ips = ['172.25.254.' + str(i) for i in range(0,255)]
print(ips)
with open(filename,'a+') as f:
for count in range(1200):
f.write(random.sample(ips,1)[0] + '\n')

#create_ip_file('ips.txt')

def sorted_ip(filename,count=10):
ips_dict = dict()
with open(filename) as f:
for ip in f:
if ip in ips_dict:
ips_dict[ip] += 1
else:
ips_dict[ip] = 1
sorted_ip = sorted(ips_dict.items(),
key= lambda x:x[1],reverse=True)[:count]
return sorted_ip
print(sorted_ip('ips.txt',20))

python中文件的讀取與寫入以及os模塊

import random
f = open('/tmp/isp1.txt','w+') #以w+模式打開創建文件
for i in range(1200):
ip = '172.25.254.'
num = random.randint(0,255) #拼接172.25.254.(num)
f.write(ip+str(num)+'\n')
f.seek(0,0) #從指針最開始讀取
s = {}
for i in f.readlines():
if i not in s :
s[i] = 1
else:
s[i] += 1
list = list(s.items())
list1 = sorted(list,key=lambda x:x[1],reverse=True)
print(list1[0:10])
f.close()#關閉文件

二。os模塊
import os

1.返回操作系統類型 值爲:posix 是linux操作系統
值爲nt 是windows操作系統
print(os.name)
print('Linux' if os.name == 'posix' else 'Windows')

2.操作系統的詳細信息
info = os.uname()
print(info)
print(info.sysname)
print(info.nodename)

3.系統的環境變量
print(os.environ)
通過key值獲取環境變量對應的value值
print(os.environ.get('PATH'))

4.判斷是否是絕對路徑
print(os.path.isabs('/tmp/ffff'))
print(os.path.isabs('hello.jog'))

5.生成絕對路徑
print(os.path.abspath('hello.png'))
print(os.path.join(os.path.abspath('.'),'hello.jpg'))
print(os.path.join('/home/kiosk','hello.jpg'))

6.獲取目錄或文件名
filename = '/home/dd/20190523/day06/hello.jpg'
print(os.path.basename(filename))
print(os.path.dirname(filename))

7.創建目錄
mkdir mkdir -p
os.mkdir('img')
os.makedirs('img/file1/file2')
不能傳歸刪除目錄
os.rmdir('img')

8.創建文件 刪除文件
os.mknod('00_ok.txt')
os.remove('00_ok.txt')

9.文件重命名
os.rename('data.txt','data1.txt

10.判斷文件或目錄是否存在
print(os.path.exists('ips.txtyyyy'))

11.分離後綴名和文件名
print(os.path.splitext('hello.jpg'))

12.將目錄名和文件名分離
print(os.path.split('/tmp/hello/hello.jpg'))

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章