python文件操作及格式化輸出


1 文件與IO

1.1讀寫文本數據

讀寫各種不同的文本數據,如ASCIIUTF-8UTF-9編碼等。

使用帶有rt模式的open()函數讀取文本文件。

例如:
with open('db', 'rt') as f:
    data = f.read()
    print(data)
with open('db', 'rt') as f:
    for line in f:
        print(line.strip('\n'))

使用帶有wtopen()函數寫入一個文本文件,如果之前文件內容存在則清除並覆蓋掉。

例如:
with open('db', 'wt') as f:
    f.write('python|python235')

如果是已存在文件中添加內容,使用atopen()函數。

操作文件時指定默認編碼

with open('somefile.txt', 'rt', encoding='latin-1') as f:
    ... 

注意:

當使用with語句時,不需要手動關閉文件,當with控制塊結束時,文件會自動關閉。不用with時,需要手動關閉。 

1.2文件不存在時寫入

在一個文件中寫入數據,如果文件不存在寫入,而不是直接覆蓋原文件內容。

例如:
with open('db', 'xt') as f:
    f.write('hello')
db文件存在拋出FileExistsError異常
Traceback (most recent call last):
  File "C:/Users/hexm/Desktop/python/s13/day3/file01.py", line 9, in <module>
    with open('db', 'xt') as f:
FileExistsError: [Errno 17] File exists: 'db'

替代方案:
import os
if not os.path.exists('db'):
    with open('db', 'wt') as f:
        f.write('hello\n')
else:
    print('File already exists')

1.3讀寫二進制文件

例如:
f = open('db', 'rb')
res = f.read()
print(res, type(res)) #b'ssssssssss' <class 'bytes'>
text = res.decode('utf-8')
print(text)

f = open('db', 'ab')
text = 'hello,世界'
f.write(bytes(text, encoding='utf-8'))
f.write(text.encode('utf-8'))

f = open('db', 'ab')
f.write(b'Hello world.')

1.4 打印輸出到文本文件

打印輸出至文件中,將print()函數輸出重定向到一個文件中。

例如:
with open('db', 'wt') as f:
    print('python1|python279', file=f)

1.5 使用其他分隔符或行終止符打印

以在print()函數中使用sepend關鍵字。

例如:
print('xiaoming', 2, 3, 5)
print('xiaoming', 2, 3, 5, sep=',', end='!!!\n')
for x in range(10):
    print(x, end=' ') #0 1 2 3 4 5 6 7 8 9 

使用str.join()也可以做到,不過str.join()僅使用於字符串。

例如:
print(','.join(str(x)for x in name)) #xiaoming,2,3,5
print(*name, sep = ',') #xiaoming,2,3,5

1.6 format格式化輸出

#format格式化輸出
s1 = 'I am {0}, age {1}'.format('hexm', 18)
print(s1) #I am hexm, age 18
s2 = 'I am {0}, age {1}'.format(*['hexm', 18])
print(s2) #I am hexm, age 18
s3 = 'I am {name}, age {age}'.format(name='hexm', age=18)
print(s3) #I am hexm, age 18
s4 = 'I am {name}, age {age}'.format(**{'name': 'hexm', 'age': 18})
print(s4) #I am hexm, age 18
監控文件尾部,並打印
#!/usr/bin/env python
# coding=utf-8

import time

def follow(thefile):
    thefile.seek(0,2)
    while True:
        line = thefile.readline()
        if not line:
            time.sleep(0.1)
            continue
        yield line

if __name__ == '__main__':
    logfile = open('/tmp/access.log', 'r')
    loglines = follow(logfile)
    for line in loglines:
        print(line.strip())
監控文件尾部,並打印,退出后從退出位置監控
#!/usr/bin/env python
# coding=utf-8
import time
import os
def follow(seek_bytes, file):
    seek_bytes = int(seek_bytes)
    file.seek(seek_bytes)  # 跳到位置信息
    while True:
        line = file.readline()
        if not line:
            time.sleep(0.1)
            continue
        else:
            # 保存位置信息
            with open('/tmp/linenumber.log', 'w+') as f:
                f.write(str(file.tell()))
            yield line
if __name__ == '__main__':
    logfile = open('/tmp/access.log', 'r')
    # 如果位置文件存在,打開並讀取
    if os.path.exists('/tmp/seek_bytes.log'):
        with open('/tmp/seek_bytes.log', 'r') as f:
            seek_bytes = f.readline().strip()
    # 位置設置為0
    else:
        seek_bytes = '0'
    # 將位置信息和文件對象傳給follow函數
    loglines = follow(seek_bytes, logfile)
    for line in loglines:
        print(line.strip())

 

 

 

 

 

 

 

 

 
        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM