Python -讀取,儲存檔案

weixin_34320159發表於2017-05-23
!/usr/bin/env python3.6
coding=utf-8
讀檔案
f = open('Test.txt') #開啟檔案
data = f.read() #讀取檔案
print(data)
# oneLine = f.readline()
# print oneLine #讀取第一行
# lines = f.readlines() #把內容按行讀取至一個list
# print lines
f.close() #關閉
寫檔案
f = open('output.txt','w') #output.txt - 檔名稱及格式 w - writing
    #以這種模式開啟檔案,原來檔案內容會被新寫入的內容覆蓋,如檔案不存在會自動建立
f.write("I'm going to write a string")
out = open('output.txt','w')
out.write("I'm Fine \nNow is raining!")
out.close()
從控制檯輸入並儲存
out = open('out.txt','w')
while True:
    data = input('Please Input something(Enter q quit): ')
    if data != 'q':
        out.write(data + '\n')
    else:
        break
從一個檔案讀取寫入到另一個檔案中
newFile = open('output.txt')
data = newFile.read()
out = open('out.txt','w')
out.write(data)
newFile.close()
out.close()
Eg:將檔案的引數讀取,並計算總和,排序
newFile = open("newFile.txt")
data = newFile.readlines()
newFile.close()
results = []

# print('所有的資料:',data) #所有的資料: ['張 23 34 45 91\n', '徐 60 77 51\n', '六 100\n', '諸葛 90 98\n']
for oneData in data:
    # print('未分割資料:',oneData) #張 23 34 45 91
    line = oneData.split() #分割字串 #['張', '23', '34', '45', '91']
    sum = 0
    for score in line[1:]:  # 切片(取姓名後面的所有成績)
        sum += int(score) #將所有的值相加
    res = '%s\t:%d\n' % (line[0], sum)
    results.append(res)

scoreFile = open('scoreFile.txt','w')
scoreFile.writelines(results)
scoreFile.close()

相關文章