• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Cheatsheet / File Handling Cheat Sheet in Python

File Handling Cheat Sheet in Python

Author: PFB Staff Writer
Last Updated: January 31, 2021

File Handling

File handling in Python requires no importing of modules.

File Object

Instead we can use the built-in object “file”. That object provides basic functions and methods necessary to manipulate files by default. Before you can read, append or write to a file, you will first have to it using Python’s built-in open() function. In this post I will describe how to use the different methods of the file object.

Open()

The open() function is used to open files in our system, the filename is the name of the file to be opened. The mode indicates, how the file is going to be opened “r” for reading, “w” for writing and “a” for a appending. The open function takes two arguments, the name of the file and and the mode for which we would like to open the file. By default, when only the filename is passed, the open function opens the file in read mode.

Example

This small script, will open the (hello.txt) and print the content. This will store the file information in the file object “filename”.


filename = "hello.txt"
file = open(filename, "r")
for line in file:
   print line,

Read ()

The read functions contains different methods, read(),readline() and readlines()


read()		#return one big string
readline	#return one line at a time
read-lines 	#returns a list of lines

Write ()

This method writes a sequence of strings to the file.


write ()	#Used to write a fixed sequence of characters to a file

writelines()	#writelines can write a list of strings.

Append ()

The append function is used to append to the file instead of overwriting it. To append to an existing file, simply open the file in append mode (“a”):

Close()

When you’re done with a file, use close() to close it and free up any system resources taken up by the open file

File Handling Examples

Let’s show some examples


To open a text file, use:
fh = open("hello.txt", "r")

To read a text file, use:
fh = open("hello.txt","r")
print fh.read()

To read one line at a time, use:
fh = open("hello".txt", "r")
print fh.readline()

To read a list of lines use:
fh = open("hello.txt.", "r")
print fh.readlines()

To write to a file, use:
fh = open("hello.txt","w")
write("Hello World")
fh.close()

To write to a file, use:
fh = open("hello.txt", "w")
lines_of_text = ["a line of text", "another line of text", "a third line"]
fh.writelines(lines_of_text)
fh.close()

To append to file, use:
fh = open("Hello.txt", "a")
write("Hello World again")
fh.close()

To close a file, use
fh = open("hello.txt", "r")
print fh.read()
fh.close()

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Cheatsheet, Files Author: PFB Staff Writer

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us