讀txt文件
fname=input('Enter filename:') // 讀取字符,與C++中的cin>>類似 try: // try...expect是python中的異常處理語句,try中寫 fobj=open(fname,'r') // 待檢測的操作語句 except IOError: // expect中寫差錯處理語句 print '*** file open error:' else: // else中處理正常情況 for eachLine in fobj: print eachLine fobj.close input('Press Enter to close')
讀txt文件內容到列表
f = open('123.txt', 'r') #文件為123.txt sourceInLines = f.readlines() #按行讀出文件內容 f.close() new = [] #定義一個空列表,用來存儲結果 for line in sourceInLines: temp1 = line.strip('\n') #去掉每行最后的換行符'\n' temp2 = temp1.split(',') #以','為標志,將每行分割成列表 new.append(temp2) #將上一步得到的列表添加到new中
print
new
最后輸出結果是:[[
'aaa'
,
'bbb'
,
'ccc'
], [
'ddd'
,
'eee'
,
'fff'
]],注意列表里存的是字符串
'aaa'
,不是變量名aaa。
寫txt文件
fname=input('Enter filename:') try: fobj=open(fname,'a') # 這里的a意思是追加,這樣在加了之后就不會覆蓋掉源文件中的內容,如果是w則會覆蓋。 except IOError: print '*** file open error:' else: fobj.write('\n'+'fangangnang') # 這里的\n的意思是在源文件末尾換行,即新加內容另起一行插入。 fobj.close() # 特別注意文件操作完畢后要close input('Press Enter to close')
新建文件
import os while True: fname=input('fname>') if os.path.exists(fname): print "Error:'%s' already exists" %fname else: break #下面兩句才是最重點。。。。也即open函數在打開目錄中進行檢查,如果有則打開,否則新建 fobj=open(fname,'w') fobj.close()