15.python OS Module
15.python OS Module
15.python OS Module
import os
#deleting the file named file3.txt
os. ("file3.txt")
• remove
Creating the new directory
• The mkdir() method is used to create the directories in the current
working directory. The syntax to create the new directory is given
below.
• Syntax:
mkdir(directory name)
Example
import os
import os
# Changing current directory with the new directiory
os.chdir("C:\\Users\\venk\\Documents")
#It will display the current working directory
os.getcwd()
Deleting directory
• he rmdir() method is used to delete the specified directory.
• The syntax to use the rmdir() method is given below.
• Syntax
os.rmdir(directory name)
• Example 1
import os
#removing the new directory
os.rmdir("directory_name")
Writing Python output to the files
• In Python, there are the requirements to write the output of a Python
script to a file.
• The check_call() method of module subprocess is used to execute a
Python script and write the output of that script to a file.
• The following example contains two python scripts. The script file1.py
executes the script file.py and writes its output to the text
file output.txt.
Example
temperatures=[10,-20,-289,100]
def c_to_f(c):
if c< -273.15:
return "That temperature doesn't make sense!"
else:
f=c*9/5+32
return f
for t in temperatures:
print(c_to_f(t))
The file related methods
SN Method Description
1 file.close() It closes the opened file. The file once closed, it can't be read or write anymore.
3 File.fileno() It returns the file descriptor used by the underlying implementation to request I/O
from the OS.
4 File.isatty() It returns true if the file is connected to a TTY device, otherwise returns false.
8 File.readlines([sizehint]) It returns a list containing all the lines of the file. It reads the file until
the EOF occurs using readline() function.
9 File.seek(offset[,from) It modifies the position of the file pointer to a specified offset with the
specified reference.
10 File.tell() It returns the current position of the file pointer within the file.