This chapter covers all the basic I/O functions available in Python. For more functions, please refer to standard Python documentation.
Printing to the Screen
The simplest way to produce output is using the print statement where you can pass zero or more expressions separated by commas. This function converts the expressions you pass into a string and writes the result to standard output as follows −
print ("Hey, How are you doing?")
This produces the following result on your standard screen −
Hey, How are you doing?
Reading Keyboard Input
Python provides two built-in functions to read a line of text from standard input, which by default comes from the keyboard. These functions are −
- input
The input Function
The input([prompt]) function is equivalent to raw_input, except that it assumes the input is a valid Python expression and returns the evaluated result to you.
str = input("Enter your Name: ") print ("Your Name is : ", str)
This would produce the following result against the entered input −
Enter your Name: prutor Your Name is : prutor
Opening and Closing Files
Until now, you have been reading and writing to the standard input and output. Now, we will see how to use actual data files.
Python provides basic functions and methods necessary to manipulate files by default. You can do most of the file manipulation using a file object.
The process of reading and writing to a file is like finding a book and opening a book.
First, the file is located, opened to the first page, then reading/writing begins until it reaches
the end of the file.The open Function
- open() returns a file object, and is most commonly used with two arguments:
open(filename, mode).Syntax
def test_files_open(): """Open files"""
Here are parameter details −
- The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used. mode can be:
-
- 'r' when the file will only be read,
-
- 'w' for only writing (an existing file with the same name will be erased),
-
- 'a' opens the file for appending; any data written to the file is automatically added to end.
-
- 'r+' opens the file for both reading and writing.
The mode argument is optional; 'r' will be assumed if it’s omitted.
Normally, files are opened in text mode, that means, you read and write strings from and to the
file, which are encoded in a specific encoding. If encoding is not specified, the default is
platform dependent (see open()). 'b' appended to the mode opens the file in binary mode: now
the data is read and written in the form of bytes objects. This mode should be used for all
files that don’t contain text.
In text mode, the default when reading is to convert platform-specific line endings (n on
Unix, rn on Windows) to just n. When writing in text mode, the default is to convert
occurrences of n back to platform-specific line endings. This behind-the-scenes modification
to file data is fine for text files, but will corrupt binary data like that in JPEG or EXE
files. Be very careful to use binary mode when reading and writing such files.
It is good practice to use the with keyword when dealing with file objects. The advantage is
that the file is properly closed after its suite finishes, even if an exception is raised at
some point. Using with is also much shorter than writing equivalent try-finally blocks:file = open("test.txt", "r") read_data = file.read() print(read_data)
The file Object Attributes
Once a file is opened and you have one file object, you can get various information related to that file.
Here is a list of all attributes related to file object −Sr.No. Attribute & Description 1 file.closed Returns true if file is closed, false otherwise.
2 file.mode Returns access mode with which file was opened.
3 file.name Returns name of the file.
4 file.softspace Returns false if space explicitly required with print, true otherwise.
Example
# Open a file file = open("test.txt", "r") print ("Name of the file: ", file.name) print ("Closed or not : ", file.closed) print ("Opening mode : ", file.mode) read_data = file.read() print(read_data)
This produces the following result −
Name of the file: test.txt Closed or not : False Opening mode : r 'hello this is sample test file'
The close() Method
The close() method of a file object flushes any unwritten information and closes the file object, after which no more writing can be done.
Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file.Syntax
fileObject.close()
Example
file = open("test.txt", "r") print ("Name of the file: ", file.name) print ("Closed or not : ", file.closed) print ("Opening mode : ", file.mode) file.close() read_data = file.read() print(read_data)
This produces the following result −
Name of the file: test.txt Closed or not : False Opening mode : r Traceback (most recent call last): File "demo.py", line 397, in <module> read_data = file.read() ValueError: I/O operation on closed file.
Reading and Writing Files
The file object provides a set of access methods to make our lives easier. We would see how to use read() and write() methods to read and write files.
The write() Method
The write() method writes any string to an open file. It is important to note that Python strings can have binary data and not just text.
The write() method does not add a newline character ('n') to the end of the string −Syntax
fileObject.write(string)
Here, passed parameter is the content to be written into the opened file.
Example
# Open a file file = open("test.txt", "w+") file.write("some contentn some more content ") # Close opend file fo.close()
The above method would create test.txt file and would write given content in that file and finally it would close that file. If you would open this file, it would have following content.
some content some more content
The read() Method
The read() method reads a string from an open file. It is important to note that Python strings can have binary data. apart from text data.
Syntax
fileObject.read([count])
Here, passed parameter is the number of bytes to be read from the opened file. This method starts reading from the beginning of the file and if count is missing, then it tries to read as much as possible, maybe until the end of file.
Example
Let's take a file test.txt, which we created above.
#Open a file file = open("test.txt", "r") read_data = file.read() print(read_data)
This produces the following result −
some content some more content
File Positions
The tell() method tells you the current position within the file; in other words, the next read or write will occur at that many bytes from the beginning of the file.
The seek(offset[, from]) method changes the current file position. The offset argument indicates the number of bytes to be moved. The from argument specifies the reference position from where the bytes are to be moved.
If from is set to 0, it means use the beginning of the file as the reference position and 1 means use the current position as the reference position and if it is set to 2 then the end of the file would be taken as the reference position.Example
Let us take a file test.txt, which we created above.
file = open("test.txt", "r+") read_file = file.read(10) print("Read String is : ", read_file) # Check current position position = file.tell() print ("Current file position : ", position) # Reposition pointer at the beginning once again reposition = file.seek(0, 0) read_file = file.read(20) print ("Again read String is : ", read_file) # Close opend file file.close()
This produces the following result −
Read String is : some conte Current file position : 10 Again read String is : some content some m
Renaming and Deleting Files
Python os module provides methods that help you perform file-processing operations, such as renaming and deleting files.
To use this module you need to import it first and then you can call any related functions.The rename() Method
The rename() method takes two arguments, the current filename and the new filename.
Syntax
os.rename(current_file_name, new_file_name)
Example
Following is the example to rename an existing file test1.txt −
import os # Rename a file from test.txt to test2.txt os.rename( "test.txt", "test2.txt")
This program stores the user's username and password in a file. Plain text files are definitely not a good way to store usernames and passwords, but this is just an example.
# Ask repeatedly until the user answers 'y' or 'n'. while True: answer = input("Have you been here before? (y/n) ") if answer == 'Y' or answer == 'y': been_here_before = True break elif answer == 'N' or answer == 'n': been_here_before = False break else: print("Enter 'y' or 'n'.") if been_here_before: # Read username and password from a file. with open('userinfo.txt', 'r') as f: username = f.readline().rstrip('n') password = f.readline().rstrip('n') if input("Username: ") != username: print("Wrong username!") elif input("Password: ") != password: print("Wrong password!") else: print("Correct username and password, welcome!") else: # Write username and password to a file. username = input("Username: ") password = input("Password: ") with open('userinfo.txt', 'w') as f: print(username, file=f) print(password, file=f) print("Done! Now run this program again and select 'y'.")
The remove() Method
You can use the remove() method to delete files by supplying the name of the file to be deleted as the argument.
Syntax
os.remove(file_name)
Example
Following is the example to delete an existing file test2.txt −
import os os.remove("test2.txt")
Directories in Python
All files are contained within various directories, and Python has no problem handling these too. The os module has several methods that help you create, remove, and change directories.
The mkdir() Method
You can use the mkdir() method of the os module to create directories in the current directory. You need to supply an argument to this method which contains the name of the directory to be created.
Syntax
os.mkdir("newdir")
Example
Following is the example to create a directory test in the current directory −
import os # Create a directory "test" os.mkdir("test")
The chdir() Method
You can use the chdir() method to change the current directory. The chdir() method takes an argument, which is the name of the directory that you want to make the current directory.
Syntax
import os os.chdir("test")
Example
Following is the example to go into "/home/newdir" directory −
import os # Changing a directory to "/home/test" os.chdir("/home/newdir")
The getcwd() Method
The getcwd() method displays the current working directory.
Syntax
os.getcwd()
Example
Following is the example to give current directory −
import os # This would give location of the current directory import os os.chdir("test") pwd = os.getcwd() print(pwd)
The rmdir() Method
The rmdir() method deletes the directory, which is passed as an argument in the method.
Before removing a directory, all the contents in it should be removed.Syntax
import os os.rmdir('dirname')
Example
Following is the example to remove "/tmp/test" directory. It is required to give fully qualified name of the directory, otherwise it would search for that directory in the current directory.
import os # This would remove "test" directory. os.rmdir( "/test" )
File & Directory Related Methods
There are three important sources, which provide a wide range of utility methods to handle and manipulate files & directories on Windows and Unix operating systems. They are as follows −
- 'r+' opens the file for both reading and writing.
- File Object Methods: The file object provides functions to manipulate files.
- OS Object Methods: This provides methods to process files as well as directories.