python 基礎 3 2 檔案 for 練習

2022-09-16 07:03:11 字數 1838 閱讀 4756

#/usr/bin/python

#coding=utf-8

#@time   :2017/11/1 22:19

#@auther :liuzhenchuan

#@file   :1030-1031練習題.py

###1 把乙個數字的list從小到大排序,然後寫到檔案中,然後從檔案中讀取檔案內容然後反序,在追加到檔案的

#下一行中

###2 分別把string list tuple dict 寫到檔案中

import codecs

l1 = [51,34,67,8,10,11,9]

l1.sort()

l2 = str(l1)

print l2

with open('a.txt','w+') as fd:

for i in l2:

fd.write(str(i))

fd.write('\n')

fd.close()

#列印出檔案內容

with open('a.txt') as fd:

print fd.read(),

#反序追加到檔案的下一行中

l1.reverse()

l3 = str(l1)

with open('a.txt','a') as fd:

for j in l3:

fd.write(str(j))

# fd.write('\n')

fd.close()

#列印出檔案內容

with open('a.txt') as fd:

print fd.read()

>>> [8, 9, 10, 11, 34, 51, 67]

[67, 51, 34, 11, 10, 9, 8]

####2 分別把string list tuple dict 寫到檔案中去

#把字串寫到檔案中去

str1= 'abcde'

with open('b.txt','w+') as f:

f.write(' '.join(str1))

with open('b.txt') as f:

print f.read()

>>> a b c d e

#把列表寫到字串中去,並用空格隔開每個字元

list1 = [1,2,3,4,5,6]

with open('c.txt','w+') as f1:

# for i in list1:

#     f1.write(str(i))

# f1.close()

f1.write(''.join([str(i)+' ' for i in list1 ]))

with open('c.txt') as f1:

print f1.read()

>>> 1 2 3 4 5 6

#把元組寫到檔案中去

tuple1 = ('1','2','a','b')

with codecs.open('d.txt','w+') as f2:

f2.write(str(tuple1) + '\n')

f2.close()

with codecs.open('d.txt') as f2:

print f2.read()

>>> ('1', '2', 'a', 'b')

#把字典寫到檔案中去

dict1 =

with open('e.txt','w+') as f3:

f3.write(str(dict1))

with open('e.txt') as f3:

print f3.read()

>>>

python基礎(13) 檔案

檔案的基本方法 可使用函式open,它位於自動匯入的模組io中。1.open函式將檔名作為唯一必不可少的引數,返回乙個可讀取的檔案物件 open a.py a.py mode r encoding cp936 2.如果要寫入檔案,必須通過指定模式來顯式地指出這一點 3.若不存在該檔案,則會產生如下錯...

python基礎(九) 檔案

file open file path,mode r 其中file path為檔案路徑 絕對路徑和相對路徑都是可以的 mode是檔案的開啟方式。open 函式會返回乙個檔案物件,我們可以通過這個檔案物件來操作檔案。file.flush 重新整理緩衝區。file.close 關閉檔案。引數值開啟方式 ...

python基礎總結4 檔案

專案 檔案的操作有三步,所有程式都一樣,就是 1.開啟檔案,或者新建檔案 2.讀 寫資料 3.關閉檔案 訪問模式說明r 以唯讀方式開啟檔案。檔案的指標將會放在檔案的開頭。這預設模式。w開啟乙個檔案只用於寫入。如果該檔案已存在則將其覆蓋。如果該檔案不存在,建立新檔案。a開啟乙個檔案用於追加。如果該檔案...