f = open ('pyehon test. txt');#Py2 can use the open or the file method for opening files, Py3 can only use open. #without arguments, open defaults to ' R ', reading, read-only mode, cannot be written and the file must exist, otherwise throws an exception. data = F.read ();#Read all content in a fileData2=f.readline ();#read a line of contentData3=f.readlines ();#reads the contents into a list by linef.close ();d= Open ('Pyehon Test 2.txt','W');#' W ' is the writing that opens the file in this mode, the contents of the original file will be overwritten by your new write, and if the file does not exist, the file will be created automatically. h = open ('Pyehon Test 3.txt','a');#' A ' is appending. It is also a write mode, but the content you write does not overwrite the previous content but is added to the file#' W ' and ' A ' mode cannot be read, only writePrint(data); H.write (data);#Write Contenth.close ();d. Close ();
#Break jumps out of the loop#continue skip this cycle#exception Handling Try ... exceptTry: I='SD'; Print(i+10);except: Print("error occurred");#DictionaryD ={};#Create an empty dictionaryd["Mylove"] ="Yanhe";#Add new KeyD[10] ='KDJF';#If your key is a string, you need to quote it when you access it by key, but not if it is a number. delD[10];#Delete a key valued["Mylove"] ="Luotianyi";#changing key values#Reference ModuleImportRandom#call module, similar to using+ class nameRandom.randint (1,10);#working with functions in a moduleDir (random);#query what functions are in random fromMathImportPi as Math_pi;#Call the PI function from the math module named Math_piPrint(MATH_PI);
Python file read and write