Python-文件讀寫和嵌套循環

一、文件讀寫

1、文件打開方式 open
fileDir = 'D:/pyTest1.txt'
fileDir2 = 'D:\\prText1.txt' #代碼層面一般用兩個\ 因爲如果文件的第一個名爲 n 就有問題了
fileDir3 = r'D:\pyText2.txt' # r取消轉義
file_object = open(fileDir,encoding='UTF-8')#如果文件中有中文,需要加一個參數:encoding='UTF-8'
print(file_object.read())#read獲取的內容是字符串  Excel的讀寫 有庫:xlrd xlwt xlutils
#文件操作完成之後要進行關閉
file_object.close()
2、文件指針—默認是0 起始位置
print(file_object.tell())#初始位置
print(file_object.read(2))
print(file_object.tell())#讀完之後的位置
3、seek 指定文件指針的位置
file_object.seek(2) #seek(位置,模式) 默認0 從0開始 1
print('seek後的文件指針位置:',file_object.tell())
#輸出:seek後的文件指針位置: 2
4、讀取一行、多行
print(file_object.readline())
#讀取多行
print(file_object.readlines())#返回列表
#去換行符讀取--返回list
print(file_object.read().splitlines())
5、文件寫入
  • w 文件存在會清空,不存在會新建

  • a 只是寫 不會清空文件,在文件末尾追加

  • r+ 爲了讀取並且寫文件而打開文件。如果文件不存在會報錯。文件指針在文件的開頭,從0開始覆蓋

  • w+ 爲了讀取並且寫文件而打開文件。如果文件不存在,會創建一個文件,文件指針在文件的開頭 如果文件已經存在,文件內容被清空

  • a+ 爲了讀取並且寫文件而打開文件。如果文件不存在,會創建一個文件。文件指針在文件的結尾。很多OS寫操作永遠在文件結尾進行,不管是否用了seek

  • 本質是寫在磁盤中,並不會寫在文件中,需要人爲去保存在文件中

  • close有關閉保存的功能

  • flush 刷新緩存

fo = open(fileDir,'w')
fo.write('12345\nabcdef')
fo.flush()
fo.close()
6、with open
with open(fileDir) as rFile,open('路徑','w') as wFile: # rFile = open()
    print(rFile.read())
    print(wFile.read())

二、循環

1、嵌套循環
boys = ['mike','jack','tom']
girls = ['lisa','aa','bb']
for girl in girls:
    for boy in boys:
#保證每個男孩對一個女孩
2、列表生成式
#對於簡單的循環,只有一層的循環可以使用列表生成式
beforetax = [10000,12000,14000,8000,4000]
aftertax = []
for one in beforetax:
    #對大於5000的扣稅
    if one > 5000:
        aftertax.append(int(one*0.9))
print(aftertax)
###列表生成式寫法
aftertax2 = [int(one*0.9) for one in beforetax if one > 5000]
print(aftertax2)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章