Python筆記(五)——檔案處理

想學生物的輪子工發表於2020-09-30

1.

# 開啟pi_digits.txt檔案
with open('pi_digits.txt') as file_object:
    contents = file_object.read()
    print(contents)  # 在read函式到達檔案末尾會返回一個空字串,顯示出來比原始檔多一個空行
    print(contents.rstrip())  # 使用rstrip函式可以刪除這個空行

filename = 'pi_digits.txt'
with open(filename) as file_object:
    for line in file_object:
        print(line)

filename = 'pi_digits.txt'
with open(filename) as file_object:
    lines = file_object.readlines()
pi_string = ''
for line in lines:
    pi_string += line.strip() #刪除空格
print(pi_string)
print(len(pi_string))

filename = 'programming.txt'
with open(filename, 'w') as file_object:  #open(filename, 'w')寫入文字並清空已有,open(filename, 'a')附加文字,不清空已有文字
    file_object.write("I love programming.")
    

 

相關文章