Python文件讀取 并按格式輸出文件內(nèi)容

需要讀取的文件內(nèi)容:http://python.itcarlow.ie/chapter3/sketch.txt

1. 切換工作目錄

代碼:

import os
os.chdir('D:/')    # 注意斜杠方向
print(os.getcwd())

輸出:

D:\

2. 打開文件open()

代碼:

try:
    data = open('sketch.txt')
    print(data.readline(), end='')    # 讀取一行內(nèi)容
    print(data.readline(), end='')    # 讀取二行內(nèi)容
    data.seek(0)    # 返回文件起始位置
except IOError:
    print('The data file is missing!')

輸出:

Man: Is this the right room for an argument?
Other Man: I've told you once.
0

3. 輸出所有內(nèi)容

代碼:

for each_line in data:
    try:
        (role, line_spoken) = each_line.split(':', 1)
        print(role, end='')
        print(' said: ', end='')
        print(line_spoken, end='')
    except ValueError:    # 因?yàn)閿?shù)據(jù)中存在多個冒號和沒有冒號的數(shù)據(jù),需要處理產(chǎn)生的錯誤,
        print(each_line)

部分輸出:

Man said:  Is this the right room for an argument?
Other Man said:  I've told you once.
... ...
Man said:  (exasperated) Oh, this is futile!!
Other Man said:  No it isn't!
Man said:  Yes it is!

4. 關(guān)閉文件

代碼:

if 'data' in locals():
    data.close()

# 或者使用with打開文件,則不需要手動close:
with open('sketch.txt', 'w') as data:

5. 完整代碼

try:
    with open('sketch.txt') as data:
        for each_line in data:
            try:
                (role, line_spoken) = each_line.split(':', 1)    # split('', 1)處理多個冒號的情況,只分一次;
                print(role, end='')
                print(' said: ', end='')
                print(line_spoken, end='')
            except ValueError:    # 因?yàn)閿?shù)據(jù)中存在沒有冒號的數(shù)據(jù),需要處理產(chǎn)生的錯誤;
                print(each_line)
except IOError as err:
    print('IOError: ' + str(err))
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容