1.read file
infile = open(fileName,'r')#for line in infile:#遍歷文件listVar = [line.rstrip() for line in infile]將每一行生成列表strVar = infile.read()#讀取文件全部內容置于一個字符串strVar = infile.readline()#讀取當前指針指向的那一行,剛開始是置于文件第一行,執行語句后,將置于末尾。準備讀取下一行infile.close()#close fileTest.txt文件中內容如下GoogleBaiduYahoo其實是以下的方式Google/nBaidu/nYahoo/n2.create file
outfile = open(fileName,'w')outfile.write(strVar)outfile.writelines(strVar)#file.write(str)的參數是一個字符串,就是你要寫入文件的內容.#file.writelines(sequence)的參數是序列,比如列表,它會迭代幫你寫入文件.outfile.close()3.opened for append
outfile = open(fileName,'a')#打開文件在文件末尾添加outfile.write(strVar)outfile.writelines(strVar)outfile.close()4.set list列表是元素的順序存儲容器,而且允許元素重復 set集合是元素的無序存儲容器,不允許元素重復
{"spam","ni"},{3,4,7},{True,7,"eleven"},{'a','b',(3,4)}#以上都是set#集合操作Word = {"spam","ni"}set.add()#word.add("eggs")#words = {"spam","ni","eggs"}set.discard()#discard丟棄,拋棄; 解雇; 出牌;word.discard("ni")words = {"spam"}set.clear()#words.clear() words = {}set#set([3,7,3])#{3,7}set#set((3,7,3))#{7,3}{x*x for x in range(-3,3)}#{0,1,4,9}set1.union(set2)#set1∪set2set1.intersection(set2)#set1∩set2set1.difference(set2)#set1-set2File1.txtAlphaBravoCharlieFile2.txtBravoDeltadef main(): infile = open("File1.txt",'r') firstSet = {line.rstrip() for line in infile} infile.close() infile = open("File2.txt",'r') firstSet = {line.rstrip() for line in infile} infile.close() outfile = open("Union.txt",'w') outfile.writelines(set1.union(set2)) outfile.close() outfile = open("Intersection.txt",'w') outfile.writelines(set1.intersection(set2)) outfile.close() outfile = open("Difference.txt",'w') outfile.writelines(set1.difference(set2)) outfile.close()main()Union.txt#Alpha,Bravo,Charlie,DeltaIntersection.txt#BravoDifference.txt#Alpha,Charlie5.csv文件 將數據以逗號分隔(當然也可以不是逗號) 譬如csvDemo.csv name,passwd,age,address zhangsan,123456,15,sichuang lisi,45612,15,jiangshu 可以在Excel中打開
UN.txtCanada,North America,34.8,385500France,Europe,66.3,211209New Zealand,Austrlia/Oceania,4.4,103738Nigeria,Africa,177.2,356669Pakistan,Asia,196.2,310403Peru,South America,30.1,496226#-----------------def main():continent = input("Enter the name of a continent:")continent = continent.title()#Allow for all lowercase lettersif continent != 'Antarctica': infile = open("UN.txt",'r') for line in infile: data = line.split(',') if data[1] == continent: PRint(data[0])else: print("There are no counteries in Antarctica")#-------Enter the name of a continent:North AmericaCanada6.dict字典
bob = {"firstName":"Robert","lastName":"Smith","age":19}print(bob["firstName"],bob["lastName"],"is",bob["age"],"years old.")[RUN]Robert Smith is 19 years old.dict操作
len(d)#字典中元素(鍵值對)的個數x in d#如果x是字典的一個鍵,返回Truex:y in d#如果x:y是字典中的元素,返回True#not ind[key1] = value1#返回key1對應的值,否者拋出異常d.get(key1,default)#如果存在key1則返回value1,否者返回defaultlist(d.keys())#返回字典鍵組成的listlist(d.values())#返回字典值組成的listlist(d.items())#返回(key,value)形成的二元組組成的列表,其中d[key]=valuelist(d)#set(d)#tuple(d)#返回字典的鍵組成的列表,集合,元組c = {}#創建一個字典c = dict(d)#創建字典d的一個拷貝d.update(c)#將字典c所有的元素合并入字典d。如果兩個元素擁有相同的鍵,則使用c中的值替換d中的值實例
eg 1:def translate(color):#英語翻譯成意大利語 if color == "red": return "rojo" elif color == "blue": return "aloz" elif color == "green": return "verdi" elif color == "white": return "blanco"#-----translate = {"red":"rojo","blue":"aloz","green":"verdi","white":"blanco"}eg 2:list1 = [["one",1],["two",2],["three",3]]或list1 = [("one",1),("two",2),("three",3)]dict(list1){"one":1,"two":2,"three":3}eg 3:Textese.txtanyone,neiare,rate,8band,b&be,b#-----def main(): texteseDict = createDictionary("Textese.txt") print("Enter a simple sentence in lowercase letters without") sentence = input("any punctuation: ") print() translate(sentence,texteseDict)def createDictionary(fileName): infile = open(fileName,'r') textList = [line.rstrip() for line in infile] infile.close() return dict([var.split(',') for var in textList])def translate(sentence,texteseDict): words = sentence.split() for word in words: print(texteseDict.get(word,word)+" ",end = " ")main()耗時2h寫好
新聞熱點
疑難解答