Lecture On Dealing With Files

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

DEALING WITH FILES IN PYTHON

let us consider that we have a file named check.txt saved in same directory as
python.

1. READ THE FILE .read()


read( ) stores every word as a string in a list.

To read the file we use the following syntax :


with open('check.txt') as check_doc: #now our doc is saved as check_doc

check_contents = check_doc.read() # contents are now in check_contents as string after.

print(cool_contents) # contents get printed on screen

2. READLINE ( )
when we don’t want every word as a string but complete sentences in a
string of list we use read lines, it is used same as .read()

syntax: .readlines( )

3. WRITING A FILE .write ()


When we want to create a file using python,
we use the same syntax but a little differently. In the open( ) we will use ‘w’ to be
able to write a file.
Syntax : with open(file_name.txt, ‘w’) as file_name:
File_contents = file_name.write(“This is just the first sentence”)
4. TO ADD SOMETHING TO THE ALREADY EXISTING FILE:
To add something to what we wrote above, we can use .write( ) but with ‘a’
instead of ‘w’ inside the open parenthesis.
Syntax = with open(file_name.txt, ‘a’) as file_name:
File_contents = file_name.write(“ \n This is the second sentence”)

You might also like