0% found this document useful (0 votes)
12 views

python_files

The document provides an overview of file handling in Python, including how to open, read, write, and delete files. It outlines different modes for file operations such as read, append, write, and create, along with examples of reading from and writing to files. Additionally, it includes instructions for checking file existence and deleting files or empty folders.

Uploaded by

madhuriravi88
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

python_files

The document provides an overview of file handling in Python, including how to open, read, write, and delete files. It outlines different modes for file operations such as read, append, write, and create, along with examples of reading from and writing to files. Additionally, it includes instructions for checking file existence and deleting files or empty folders.

Uploaded by

madhuriravi88
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

File Handling in Python

BASIC STUFF

# opening a file for reading


file = open('filename')

# opening a file for the specified mode


file = open('filename', 'mode')

# shorthand read/write with close


with open('filename', 'mode') as file:
statements

MODES OF FILE HANDLING

Action

Read Mode( "r" ): Default value. Opens a file for reading, error if the file does not exist.
Append Mode( "a" ): Opens a file for appending, creates the file if it does not exist.
Write Mode( "w" ): Opens a file for writing, creates the file if it does not exist.
Create Mode( "x" ): Creates the specified file, returns an error if the file exists.

Type of file

Text( "t" ): Default mode. Text mode.


Binary( "b" ): For binary files (eg. images)

READING FROM A FILE

# opening file to read


file = open("hello.txt")

# reading the entire file at once


file.read()

# only read first n characters of the file


file.read(n)

# read a single line from the file


file.readline()

# read all lines of the file as an array of strings


file.readlines()

# close file after use


file.close()

WRITING TO A FILE

# opening file to write


file = open('hello.txt', 'a') # append content
file = open('hello.txt', 'w') # overwrite content
file = open('hello.txt', 'x') # create file if it doesn't exist

# write a whole string to a file


file.write('Hello World!!')

# close file after use


file.close()

DELETING FILES

# deleting a file
import os
os.remove('hello.txt')

# check if file exists


import os
print(os.path.exists('hello.txt'))

# delete an empty folder


import os
os.rmdir('empty_folder')

SilicoFlare
 silicoflare@gmail.com
󰙯 @silicoflare

You might also like