Python Input And Output
Python provides methods that can be used to read and write data. Python also provides supports of reading and writing data to Files.
print()
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("Hello ApkZube")
x=150
print(x)
output of above example :
Hello ApkZube
150
Input from Keyboard :
In Python 3, raw_input() function is deprecated. Moreover, input() functions read data from keyboard as string, irrespective of whether it is enclosed with quotes ('' or "" ) or not.
- input() - 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.
def cube(x):
return x*x*x
a=int(input("Enter number :"))
print("cube of ",a," is ",cube(a))
output of above example :
Enter number :10
cube of 10 is 1000
Python File Handling
Python provides the facility of working on Files. A File is an external storage on hard disk from where data can be stored and retrieved.
- Opening a File - Before working with Files you have to open the File. To open a File, Python built in function open() is used. It returns an object of File which is used with other functions. Having opened the file now you can perform read, write, etc. operations on the File.
- closing file - 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.
file_object = open(file_name [, access_mode][, buffering])
Here are parameter details −
- file_name − The file_name argument is a string value that contains the name of the file that you want to access.
- access_mode − The access_mode determines the mode in which the file has to be opened, i.e., read, write, append, etc. A complete list of possible values is given below in the table. This is an optional parameter and the default file access mode is read (r).
- buffering − If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line buffering is performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior).
Comparision operators in Python
mode | description |
---|---|
r | Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode. |
rb | Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode. |
r+ | Opens a file for both reading and writing. The file pointer placed at the beginning of the file. |
rb+ | Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file. |
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. |
wb | Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. |
w+ | Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. |
wb+ | Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. |
a | Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. |
ab | Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. |
a+ | Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. |
ab+ | Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. |
The file Object Attributes
- 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 :
# Open a file
data = open("data.txt", "wb")
print ("Name of the file: ", data.name)
print ("Closed or not : ", data.closed)
print ("Opening mode : ", data.mode)
data.close() #closed data.txt file
output of above example :
Name of the file: data.txt
Closed or not : False
Opening mode : wb
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.
- write() - 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 .
file_object.write(string)
example :
# Open a file
data = open("data.txt", "w")
data.write("Welcome to ApkZube's Python Tutorial")
print("done")
data.close()
output of above example :
done
- read() - 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.
file_object.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.
# Open a file
data = open("data.txt", "r+")
file_data = data.read(18) # read 18 byte only
full_data = data.read() #read all byte into file from last cursor
print(file_data)
print(full_data)
data.close()
output of above example :
Welcome to ApkZube
's Python Tutorial
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, the beginning of the file is used as the reference position. If it is set to 1, the current position is used as the reference position. If it is set to 2 then the end of the file would be taken as the reference position.
# Open a file
data = open("data.txt", "r+")
file_data = data.read(18) # read 18 byte only
print("current position after reading 18 byte :",data.tell())
data.seek(0) #here current position set to 0 (starting of file)
full_data = data.read() #read all byte
print(file_data)
print(full_data)
print("position after reading file : ",data.tell())
data.close()
output of above example :
current position after reading 18 byte : 18
Welcome to ApkZube
Welcome to ApkZube's Python Tutorial
position after reading file : 36
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.
- rename() - The rename() method takes two arguments, the current filename and the new filename.
syntax ;
os.rename(current_file_name, new_file_name)
import os
os.rename('data.txt','my_data.txt')
output of above example :
- remove() - 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)
import os
os.remove('my_data.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
- mkdir() - 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("dir_name")
import os
os.mkdir('apkzube')
- chdir() - 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 :
os.chdir("newdir")
import os
# Changing a directory to "/home/newdir"
os.chdir("/home/newdir")
- getcwd() - The getcwd() method displays the current working directory.
import os
print(os.getcwd())
output of above example :
/home
- rmdir() - 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
import os
# This would remove "/home/apkzube" directory.
os.rmdir( "/home/apkzube" )
result :
apkzube dir will be removed.
No comments:
Post a Comment