10 File Handling

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

1/16/22, 7:50 AM 10 File Handling

File Handling
The key function for working with files in Python is the open() function.

The open() function takes two parameters; filename, and mode.

"r" - Read - Default value. Opens a file for reading, error if the file does not exist

"a" - Append - Opens a file for appending, creates the file if it does not exist

"w" - Write - Opens a file for writing, creates the file if it does not exist

"x" - Create - Creates the specified file, returns an error if the file exists

"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (e.g. images)

'+' Open a file for updating (reading and writing)

In [2]:
# python will be saving ion Default Path to know the path

# To change the direcory

#os.chdir(''C:\\Users\\rgandyala\\2. Python Course'')

import os

os.getcwd()

Out[2]: 'C:\\Users\\rgandyala\\2. Python Course'

In [3]:
f = open("python.txt") # permission to open the file

Out[3]: <_io.TextIOWrapper name='python.txt' mode='r' encoding='cp1252'>

In [4]:
# Read will be command to read the file which we have opened

test = f.read()

In [5]:
test

Out[5]: 'this is a new test document which has more content'

In [6]:
# r" - Read - Default value. Opens a file for reading, error if the file does not exist

In [7]:
file1=open("python.txt",mode="r")

file:///C:/Users/rgandyala/Downloads/10 File Handling.html 1/5


1/16/22, 7:50 AM 10 File Handling
data=file1.read()#read data from file

print(data)

this is a new test document which has more content

In [8]:
# Close is function to name to close the opened files

file1.close()

In [9]:
#Read Only Parts of the File

#we can specify the how many character you want to

f = open("python.txt", "r")

print(f.read(11))

this is a n

In [4]:
#ReadLines - it will read one line at a time

f = open("file.txt", "r")

print(f.readline())

hello world

In [13]:
# If you want to read multiple lines call readline two times

f = open("file.txt", "r")

print(f.readline())

print(f.readline())

hello world

welcome to Data Science

Write to an Existing File


In [10]:
# "a" - Append - will append to the end of the file

# "w" - Write - will overwrite any existing content

In [1]:
f = open("python.txt", mode="a")

f.write(" Now the file has more content!")

f.close()

In [11]:
f = open("python.txt", mode= "r")

file:///C:/Users/rgandyala/Downloads/10 File Handling.html 2/5


1/16/22, 7:50 AM 10 File Handling

In [12]: print(f.read())

this is a new test document which has more content Now the file has more content!

In [14]:
# "w" - Write - will overwrite any existing content

In [4]:
file2=open("python2.txt",mode="w") # creaet the new file python2.txt

file2.write("this is a new test document which has more content") # write the content a

Out[4]: 50

In [7]:
file2 = open("python2.txt", mode= "r") # open that newl created file

In [8]:
print(file2.read()) # read the file and print the value

this is a new test document which has more content

In [9]:
b = open("python.txt", mode="r")

b.read()

Out[9]: 'this is a new test document which has more content Now the file has more content!'

In [12]:
# tell method will show the current position - size

b.tell()

Out[12]: 50

In [25]:
#Seek bring the cursor to intial position

b.seek(0)

Out[25]: 0

In [23]:
# Writing to File or creating a file from jupter

In [10]:
f = open("test13.txt", "w")

f.write("This is a First File\n")

f.write("Contains two lines\n")

f.close()

In [13]:
f = open("test13.txt",mode="r")

In [14]:
f.read()

file:///C:/Users/rgandyala/Downloads/10 File Handling.html 3/5


1/16/22, 7:50 AM 10 File Handling

Out[14]: 'This is a First File\nContains two lines\n'

In [23]:
# \n Indicate the new line in the file

f.close()

In [ ]:

In [19]:
file1=open("data.txt",mode="r+")

data=file1.read()#read data from file

# print the data

print(data)

# Read the file and update the sentence

file1.write("this test for2 r+")

file1.close()

this test for2 r+

In [20]:
data

Out[20]: 'this test for2 r+'

Renaming And Deleting Files In Python.


In [ ]:
# Renaming File

In [16]:
import os

In [26]:
os.rename("data.txt","NewData.txt")

In [27]:
os.rename("NewData.txt","data.txt")

In [33]:
# Removing File

In [28]:
# we can remove the files which are closed - Opened files we cannot remove.

# To remove the files we use code of f.close()

os.remove("test.txt")

Python Directory

In [54]:
os.getcwd()

Out[54]: 'C:\\Users\\rgandyala\\2. Python Course'

In [ ]:
file:///C:/Users/rgandyala/Downloads/10 File Handling.html 4/5
1/16/22, 7:50 AM 10 File Handling
# Change the Directory with Chdir command and providing path

os.chdir("/users/filenae")

List Directories and Files


All files and sub directories inside a directory can be known using the
listdir() method.

In [19]:
os.listdir(os.getcwd())

Out[19]: ['.ipynb_checkpoints',

'10 File Handling.ipynb',

'11 Exception Handling.ipynb',

'data.txt',

'file.txt',

'python.txt',

'test.txt',

'test2.txt']
Making New Directory

We can make a new directory using the mkdir() method.

This method takes in the path of the new directory.

If the full path is not specified, the new directory is created in the current working directory.

In [20]:
os.mkdir('test')

Remove Directory

rmdir() method can only remove empty directories.

In order to remove a non-empty directory we can use the rmtree() method inside the shutil module.

In [35]:
os.rmdir('test')

In [ ]:
import pandas as pd

pd.read_CSV("path")

In [ ]:

file:///C:/Users/rgandyala/Downloads/10 File Handling.html 5/5

You might also like