Python file read and write

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.