Repository navigation
Files
This chapter covers all the basic I/O functions available in Python 3. For more functions, please refer to the standard Python documentation.
The input([prompt]) function is equivalent to raw_input, except that it assumes that the input is a valid Python expression and returns the evaluated result to you.
Example:
#!/usr/bin/python3
>>> x = input("something:")
something:10
>>> x
'10'
>>> x = input("something:")
something:'10' #entered data treated as string with or without ''
>>> x
"'10'"Before you can read or write a file, you have to open it using Python's built-in open() function. This function creates a file object, which would be utilized to call other support methods associated with it.
Example:
file object = open(file_name [, access_mode][, buffering])Here is a list of the different modes of opening a file:
r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
And many others
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 the attributes related to a file object:
file.closed # Returns true if file is closed, false otherwise.
file.mode # Returns access mode with which file was opened.
file.name # Returns name of the file.Example:
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
print ("Closed or not : ", fo.closed)
print ("Opening mode : ", fo.mode)
fo.close()Result:
Name of the file: foo.txt
Closed or not : False
Opening mode : wb
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.
Example:
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
# Close opened file
fo.close()Result:
Name of the file: foo.txt
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.
Note: The write() method does not add a newline character ('\n') to the end of the string.
Example:
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "w")
fo.write( "Python is a great language.\nYeah its great!!\n")
# Close opend file
fo.close()Result:
Python is a great language.
Yeah its great!!
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.
Example:
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10)
print ("Read String is : ", str)
# Close opened file
fo.close()Result:
Read String is : Python is
Python os module provides methods that help you perform file-processing operations, such as renaming and deleting files.
The rename() method takes two arguments, the current filename and the new filename.
Example:
#!/usr/bin/python3
import os
# Rename a file from test1.txt to test2.txt
os.rename( "test1.txt", "test2.txt" )You can use the remove() method to delete files by supplying the name of the file to be deleted as the argument.
Example:
#!/usr/bin/python3
import os
# Delete file test2.txt
os.remove("text2.txt")You can use the mkdir() method of the os module to create directories in the current directory.
Example:
#!/usr/bin/python3
import os
# Create a directory "test"
os.mkdir("test")You can use the chdir() method to change the current directory.
Example:
#!/usr/bin/python3
import os
# Changing a directory to "/home/newdir"
os.chdir("/home/newdir")The getcwd() method displays the current working directory.
Example:
#!/usr/bin/python3
import os
# This would give location of the current directory
os.getcwd()The rmdir() method deletes the directory, which is passed as an argument in the method.
Note: Before removing a directory, all the contents in it should be removed.
Example:
#!/usr/bin/python3
import os
# This would remove "/tmp/test" directory.
os.rmdir( "/tmp/test" )