读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()