This chapter covers all the basic I/O functionality used in Python. Refer to the standard Python documentation for more functions.
to print to the screen:
The simplest way to produce output is to use the print statement, which can be separated by a comma of 0 or more expressions. The function is passed to a string expression, and the result is written to standard output, as follows:
#!/usr/bin/pythonprint "Python is really a great language,", "isn ' t it?";
This will produce the result output on the standard screen with the following results:
Python is really a great language, isn ' t it?
Read keyboard input:
Python provides two built-in functions to read a line from standard input, which by default is text from the keyboard. These functions include:
Raw_input function:
The Raw_input ([prompt]) function reads a row from the standard input and returns a string (minus the end of the line break).
#!/usr/bin/pythonstr = Raw_input ("Enter Your input:");p rint "Received input is:", str
This prompts you to enter a string that will display the same string on the screen. When you enter "Hello python!", its output is this:
Enter your Input:hello pythonreceived input Is:hello Python
Input function:
The input ([prompt]) function is equivalent to raw_input, except that it assumes that the input is a valid Python expression and returns the result of the calculation.
#!/usr/bin/pythonstr = input ("Enter your input:");p rint "Received input is:", str
For the input this will produce the following results:
Enter your input: [x*5 for X in range (2,10,2)]recieved input is: [10, 20, 30, 40]
To open and close a file:
Until now, read and write standard inputs and outputs have been understood. Now, let's look at how to use the actual data file.
Python provides basic functions and the necessary ways to manipulate files by default. You can do most of the file operation using a file object.
Open function:
To read or write to a file, you must use the Python built-in open () function to open it. This function creates a file object that will be used to invoke other support methods associated with it.
Grammar:
File Object = open (file_name [, access_mode][, Buffering])
The following is the details of the parameters:
- The File_name:file_name parameter is a string value that contains the name of the file that you want to access.
- Access_mode:access_mode decides that the file must be opened, i.e., read, write, append, etc. the possible values are given in the table below for a complete list of patterns. This is an optional parameter and the default file access mode is read (R).
- Buffering: If the buffer value is set to 0 o'clock, no buffering will occur. If the buffer value is 1, the row buffer is accessed by a file to execute. If the specified buffer value is an integer greater than 1, the buffering action is made with the size of the indicated buffer. If negative, the size of the buffer is the system default (the default behavior).
Here is a list of different modes for opening a file:
File Object properties:
Once the file is opened, the file object can get various information about the file.
The following is a list of all the properties related to the file object:
Example:
#!/usr/bin/python# Open a filefo = open ("Foo.txt", "WB") print "Name of the file:", Fo.nameprint "Closed or not:", fo.cl Osedprint "Opening mode:", Fo.modeprint "Softspace flag:", Fo.softspace
This will produce the following results:
Name of the file:foo.txtClosed or not:falseopening mode:wbsoftspace flag:0
Close () Method:
The close () method of a file object flushes the information that is not written, and closes the object of the file, after which no data content can be written.
Python automatically shuts down when a file's Reference object is reassigned to another file. It is a good practice to use the close () method to close a file.
Grammar:
Fileobject.close ();
Example:
#!/usr/bin/python# Open a filefo = open ("Foo.txt", "WB") print "Name of the file:", fo.name# Close opend filefo.close ()
This will produce the following results:
Name of the File:foo.txt
Read and Write files:
The file object provides a set of access methods. Let's look at how to read and write to the file using the read () and write () methods.
Write () Method:
The write () method writes a string to any open file. Note that a Python string can have binary data, not just text.
The Write () method does not add a newline character (' \ n ') to the end of the string:
Grammar:
Fileobject.write (string);
Here, the passed parameter is the content to be written to the open file.
Example
#!/usr/bin/python# Open a filefo = open ("Foo.txt", "WB") fo.write ("Python is a great language.\nyeah its great!! \ n "); # Close opend filefo.close ()
The method above creates a foo.txt file, writes the given content to the file, and eventually closes the file.
Python is a great language. Yeah its great!!
Read () Method:
The Read () method reads a string of open files. Note that a Python string can have binary data, not just text.
Grammar
Fileobject.read ([count]);
Here, the parameter passed is the number of bytes read out from the open file. This method reads from the beginning of the file, and if the count is lost, then it tries to read as much as possible until the end of the file.
Example:
Here is an example of a file Foo.txt, which was created above.
#!/usr/bin/python# Open a filefo = open ("Foo.txt", "r+") str = Fo.read (Ten);p rint "Read String is:", str# Close opend file Fo.close ()
This will produce the following results:
Read String Is:python is
File Location:
The Tell () method tells the current position in the file; in other words, the next read or write will occur at the beginning of the file from the number of bytes.
The Seek (offset[, from]) method changes the current file location. The offset parameter indicates the number of bytes to move. Specifying bytes from this parameter is moved to the reference point.
If the from is set to 0, which means that the beginning of the file is used as the base position, and set to 1 is using the current position as the base position, and if it is set to 2, the end of the file will be used as the base position.
Example
Let's take a file foo.txt, which is created above.
#!/usr/bin/python# Open a filefo = open ("Foo.txt", "r+") str = Fo.read (Ten);p rint "Read String is:", str# Check Current PO Sitionposition = Fo.tell ();p rint "Current file position:", position# reposition pointer at the beginning once Againposit Ion = Fo.seek (0, 0); str = fo.read;p rint "Again read String is:", str# Close opend filefo.close ()
This will produce the following results:
Read string Is:python iscurrent file Position:10again Read string Is:python is
To rename and delete files:
The Python OS module provides methods to help perform file processing operations such as renaming and deleting files.
To use this module, you need to import it first and then invoke the relevant functionality.
Rename () Method:
The rename () method has two parameters, the current file name, and a new file name.
Grammar:
Os.rename (Current_file_name, New_file_name)
Example
The following is an example to rename a file Test1.txt:
#!/usr/bin/pythonimport os# Rename A file from Test1.txt to Test2.txtos.rename ("Test1.txt", "Test2.txt")
Remove () Method:
You can use the Remove () method to provide a parameter as the file name for the file you want to delete.
Grammar:
Os.remove (file_name)
Example
The following example deletes an existing file test2.txt:
#!/usr/bin/pythonimport os# Delete file Test2.txtos.remove ("Text2.txt")
Directories in Python:
All the files are contained in different directories, and there is no problem dealing with them in Python. There are several ways the OS module can help create, delete, and change directories.
MkDir () Method:
You can use the mkdir () method of the OS module to create a directory under the current directory. You need to provide the parameter, this method contains the name of the directory to be created.
Grammar:
Os.mkdir ("Newdir")
Example:
The following example creates the test directory under the current directory as follows:
#!/usr/bin/pythonimport os# Create a directory "test" Os.mkdir ("test")
ChDir () Method:
You can use the ChDir () method to change the current directory. The ChDir () method takes a parameter, which is the name of the directory to be the current directory.
Grammar:
Os.chdir ("Newdir")
Example:
Here is an example of entering the "/home/newdir" directory:
#!/usr/bin/pythonimport os# Changing a directory to "/home/newdir" Os.chdir ("/home/newdir")
GETCWD () Method:
The GETCWD () method displays the current working directory.
Example:
OS.GETCWD ()
Example:
The following is an example given as the current directory:
#!/usr/bin/pythonimport os# This would give location of the current DIRECTORYOS.GETCWD ()
RmDir () Method:
The rmdir () command method deletes the directory, which is the parameter through the method.
When you delete a directory, all of its contents should be deleted.
Grammar:
Os.rmdir (' dirname ')
Example
The following is an example of deleting the "/tmp/test" directory. It is required to get the full name of the directory, otherwise the directory will be searched in the current directory.
#!/usr/bin/pythonimport os# This would remove "/tmp/test" Directory.os.rmdir ("/tmp/test")