About Python file processing--file input and output

Source: Internet
Author: User
Tags file copy rewind

Let's briefly introduce Some of the most common ways of IO in Python. Of course, in addition to the following methods, you can also refer to the Python manual, for example, I would like to find the use of the Raw--input function, I can directly use the command: Python-m pydoc raw_input (under Windows) to see the usage of the method, When you are finished using, enter "Q" as the exit. Below to get to the chase:

First, the input in Python

1. "Game" with command line--raw_input function

#Input: Age= Raw_input ("How is old is you ?") Height= Raw_input ("How tall is you ?") Weight= Raw_input ("How much does you weigh?")Print "So, you ' re%r old,%r tall and%r heavy."%(age, height, weight)#Output:How is old is you ?35How tall is you ?6'2 "How much does weight? 180lbsSo, you'Re'35'Old ,'6\'2 "'Tall and '180lbs'Heavy.

Note: here %r is debug - Specific, it shows the original representation of the character, but also often see the use of %s , %s is the string to display to the user.

2. "Reading" from the parameter--passing the variable to the script

#Input: fromSysImportArgvscript, first, second, third=argvPrint "The script is called:", ScriptPrint "Your First variable is:", FirstPrint "Your Second variable is:", SecondPrint "Your Third variable is:", Third#Output:python ex13.py cheese apples breadthe script iscalled:ex13.pyYour First variable is: Cheeseyour Second variable is: applesyour Third variable is: Bread

3. Listen to the "content" of the file--read the file with great tips

Suppose we now have two files, one is the script file ex.py , the other is ex_sample.txt, the second

File is a text file for your script to read. Suppose the contents of a second file:

This is the stuff I typed into a file.

It is really cool stuff.

Lots and Lots of fun to has in here.

All we have to do is put the file in our script "open " and print it out. However, the file name

Ex_sample.txt Writing Dead (hardcode) is not a good idea in the code, it should be the user input. If we encounter other files to deal with, writing dead filenames will cause you trouble. Our solution is to use argv and raw_input to get information from users to know which files should be processed.

#Input: fromSysImportargvscript, filename=Argvtxt=open (filename)Print "Here ' s your file%r:"%filenamePrintTxt.read ()#Output:python ex.py ex_sample.txt here's your file'Ex_sample.txt': This isstuff I typed into a file. It isreally cool stuff. Lots andLots of funinchHere .

Extension:txt = open (filename) is the contents of the file returned? No, it returns a thing called "File Object" that you can think of as a tape drive or DVD player. You can freely access any location of the content and read the content, but the object itself is not its content.

Second, read and write files

1. Commonly read and write file functions--Han Xin Soldiers of:

close– Close the file. File with your editor

Empty the file and rewrite the file

Example:

Print "Opening the file ..."Target= open (filename,'W')Print "truncating the file. goodbye!"target.truncate ()Print "Now I ' m going-to-ask for three lines."line1= Raw_input ("Line 1:") Line2= Raw_input ("Line 2:") Line3= Raw_input ("Line 3:")Print "I ' m going to write these to the file."target.write (line1) target.write ("\ n") Target.write (line2) target.write ("\ n") Target.write (line3) target.write ("\ n")Print "and finally, we close it."target.close ()

2. Other file operation--Eight Immortals crossing, recount

File copy

Example:

 fromSysImportargv fromOs.pathImportExistsscript, From_file, To_file=argvPrint "Copying from%s to%s"%(From_file, To_file)#we could do these the one line too?In_file=Open (from_file) Indata=In_file.read ()Print "The input file is%d bytes long"%Len (indata)Print "Does The output file exist?%r"%exists (to_file)Print "Ready , hits RETURN to continue, ctrl-c to abort."raw_input () out_file= Open (To_file,'W') Out_file.write (indata)Print "Alright, all done."out_file.close () in_file.close ( )

Combining files and functions

Example:

 fromSysImportArgvscript, Input_file=argvdefPrint_all (f):PrintF.read ()defRewind (f): F.seek (0)defPrint_a_line (Line_Count, f):PrintLine_Count, F.readline () Current_file=Open (input_file)Print "First let ' s print the whole file:\n"Print_all (current_file)Print "Now let's rewind, kind of like a tape."Rewind (Current_file)Print "Let ' s print three lines:"Current_line= 1print_a_line (Current_line, current_file) current_line= Current_line + 1print_a_line (Current_line, current_file) current_line= Current_line + 1print_a_line (Current_line, Current_file)

where Seek (0) indicates where the file was found to begin.

Additional: Methods for multi-line output

Print "" "

Alright, so-said%r about liking me.

You live in%r. Not sure where the IS.

And you have a%r computer. Nice.

"" "% (likes, lives, computer)

About Python file processing--file input and output

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.