Thursday, June 22, 2023

Python File I/O

 

               Python File I/O

 

Permanent  Storage of data

·     open  a file

·     read or write(perform operation)

·     close the file

    How to Open a file? 

>>> f=open("txt.txt",'w')    #open file in current directory

>>> f=open("c:/python33/README.txt")  #specifying full path

 

Python File Modes

mode

Description

'r'          

'w'

 

 

'x'

 

 

'a'

 



 't'

 

'b'

 

'+'

open a file for reading.(default)

open a file for writing .creates a new file if it does not exists  or truncates the file if it exists.

Open a file for exclusive creation.

If the file already exists,the operation  fails.

Open for appending at the end of the file without truncating it.creates a new file if it does not exists.

 

Open in text module.(default)

 

Open in binary mode.

 

Open a  file for updating(reading and writing)

 

How to close a file using python?

f=open("text.txt",'w',encoding='utf-8')

# perform file operations

f.close()

 Creating a file using try ... finally block

try:

       f=open("text.txt",'w',encoding='utf-8')

#perform file operations

finally:

     f.close()

How to write to file using python?

with open("text.txt",'w',encoding='utf-8')as f:

f.write("my first file\n")

f.write("This file\n\n")

f.write("contains three lines\n")

How to read files in python?

>>>f=open("text.txt",'r',encoding= 'utf-8')

>>>f.read(4)   #read the first 4 data

'This'

>>>f.read(4)    #read the next 4 data

' is '

>>>f.read()      #read in the rest till end of file

'my first file

This file

contains three lines'

>>>f.read()    #further reading returns empty string

''

>>>f.tell()

56

>>>f.seek(0)

0

>>>print(f.read())

This is my first file

This file

contains three lines

 #readline() reads every line in file

>>>f.readline()

'This is my first file\n'

>>>f.readline()

'This file\n'

>>>f.readline()

'contains three lines\n'

>>>f.readline()

' '

Example#1

Tfile=open("hai.txt","w")

Tfile.write("hai\n")

Tfile.write("hello\n")

Tfile.write("how are you")

Tfile.close()

print("\n"*50)

Tfile=open("hai.txt","r")

for line in Tfile:

     print(line)

Tfile.close()

 Output



after 50 lines



hai

hello

how are you

File Creation(Write Datas  Into A File)

jkfile=open("biodata.txt","w")

ch='y'

while ch=='y':

          x=input("enter a name...")

          jkfile.write(x+"\n")

          ch=input("continue..[y/n]:")

jkfile.close()

when we execute this program prompt like the following:-

enter name...KANNADASAN

continue..[y/n]:Y

enter a name...DHANDAPANI

continue..[y/n]:Y

enter a name...KARTHICK

continue..[y/n]:Y

enter a name....KARUNAKARAN

continue...[y/n]:N

File Processing (Display Data From The Existing File)

jkfile=open("biodata.txt","r")

for i in jkfile:

    print(len(i))

    print(i)

jkfile.close()

 

output

11

KANNADASAN

11

DHANDAPANI

9

KARTHICK

12

KARUNAKARAN

PYTHON DIRECTORY AND FILES MANAGEMENT

get current directory

>>> import os

>>> os.getcwd()

'C:\\Python27'

>>>os.getcwdb()

b'c;\\program files\\pyscripter'

>>>print(os.getcwd())

c:\program files\pyscripter

changing directory

>>>os.chdir('c:\\python33')

>>>print(os.getcwd())

c:\python33

List directories and files

>>> print(os.getcwd())

C:\Python27

>>>os.listdir()

['DLL',

'doc',

'include',

'lib',

'LICENSE.txt',

'NEWS.txt',

'python.exe',

pythonw.exe',

'README.txt',

'scripts',

'tcl',

'tools']

>>> os.listdir('G:\\')

['$RECYCLE BIN',

'movies',

'music',

'photos',

'series',

'system volume information']

Making a new directory

mkdir() method

>>>os.mkdir('test')

>>> os.listdir()

['test']

Renaming a directory or a file

>>>os.listdir()

['test']

>>>os.rename('test','new_one')

>>>os.listdir()

['new_one']

Removing Directory or file

>>>os.listdir()

['new_one','old.txt')

>>>os.remove('old.txt')

>>>os.listdir()

['new_one']

>>>os.rmdir('new_one')

>>>os.listdir()

[]

>>>os.listdir()

['test']

>>>os.rmdir('test')

traceback(most recent call last):

....

OSError:

[winError 145] Thedirectory is not empty:'test'

>>> import shutil

>>>shutil.rmtree('test')

>>>os.listdir()

[]

0 comments:

Post a Comment