SlideShare a Scribd company logo
 
 
 
Python 3.x - File Objects Cheatsheet 
   
1
Reading files 
● To open a file and read: ​f = open(​'name-of-the-file.txt'​, ​'r'​)
● To open a file and write: ​f = open(​'name-of-the-file.txt'​, ​'w'​)
● To open a file and append(this is done to avoid overwriting of a file and include extra chunk of text to
the file which has already been created): ​f = open(​'name-of-the-file.txt'​, ​'a'​)
● To open a file and read and write: ​f = open(​'name-of-the-file.txt'​, ​'r+'​)
● Prints the name of the file: ​print(f.name)
● Prints the mode if file is read or write mode: ​print(f.mode)
● Prints the file contents in the python interpreter or terminal/cmd: ​print(f.read)
● Reads the first line. Will read second line if this method is called again:
f_contents = f.readline()
print(f_contents)
● Reads each line of the .txt file and stores it in a list variable:
f_contents = f.readlines()
print(f_contents)
● Download the files: mbox.txt and mbox-short.txt for practice from: ​www.py4e.com/code3/mbox.txt
and ​www.py4e.com/code3/mbox-short.txt
● To read each lines of the whole file in traditional way:
fname = input(​'Enter the file name: '​)
try​:
fhand = open(fname, ​'r'​)
# Reads each line in the file
count = 0
for​ line ​in​ fhand:
# end = '' removes extra line
print(line, end=​''​)
count = count + 1
fhand.close()
except​ FileNotFoundError:
print(​'File: '​ + fname + ​' cannot be opened.'​)
# Terminates the program
exit()
print(​'There were'​, count, ​'subject lines in'​, fname)
● To read a line which starts with string ​'From:'​:
for​ line ​in​ fhand:
​if​ line.startswith(​'From:'​):
print(line, end=​''​)
2
● To read the whole file:
fname = input(​'Enter the file name: '​)
try​:
fhand = open(fname, ​'r'​)
text = fhand.read()
fhand.close()
except​ FileNotFoundError:
print(​'File cannot be opened:'​, fname)
exit()
print(text)
● To read each line of the file and the line starting from ​'From:'​ using context manager:
fname = input(​'Enter the file name: '​)
try​:
​with​ open(fname, ​'r'​) ​as​ f:
​for​ line ​in​ f:
​if​ line.startswith(​'From:'​):
print(line, end=​''​)
except​ FileNotFoundError:
print(​'File cannot be opened:'​, fname)
exit()
● To read whole file using context manager:
fname = input(​'Enter the file name: '​)
try​:
​with​ open(fname, ​'r'​) ​as​ f:
text = f.read()
except​ FileNotFoundError:
print(​'File cannot be opened:'​, fname)
exit()
print(text)
● To read specified number of characters from the file:
fname = input(​'Enter the file name: '​)
with​ open(fname, ​'r'​) ​as​ f:
size_to_read = 10
f_contents = f.read(size_to_read)
# Infinite loop for testing
3
while​ len(f_contents) > 0:
​# To identify if we are looping through 10
​# characters at a time use end='*'
print(f_contents, end=​'*'​)
Write to files 
● To make a new file and write to it:
fout = open(​'out.txt'​, ​'w'​)
line1 = ​"This here's the wattle, n"
fout.write(line1)
line2 = ​'the emblem of our land.n'
fout.write(line2)
● To make a copy of the file:
fname = input(​'Enter the file name: '​)
with​ open(fname, ​'r'​) ​as​ rf:
with​ open(fname[:-4] + ​'_copy.txt'​, ​'w'​) ​as​ wf:
for​ line ​in​ rf:
wf.write(line)
● To add content to an already written file such that overwriting doesn’t occur by going append mode
from write mode:
oceans = [​"Pacific"​, ​"Atlantic"​, ​"Indian"​, ​"Southern"​, ​"Arctic"​]
with​ open(​"oceans.txt"​, ​"w"​) ​as​ f:
for​ ocean ​in​ oceans:
print(ocean, file=f)
with​ open(​"oceans.txt"​, ​"a"​) ​as​ f:
print(23*​"="​, file=f)
print(​"These are the 5 oceans."​, file=f)
● To make a copy of other files such as .jpeg and .pdf, read binary and write binary mode has to be
enabled:
with​ open(​'file-of-your-choice.jpg'​, ​'rb'​) ​as​ rf:
​with​ open(​'file-of-your-choice_copy.jpg'​, ​'wb'​) ​as​ wf:
​for​ line ​in​ rf:
wf.write(line)
4
References 
YouTube. 2018. Python Tutorial: File Objects - Reading and Writing to Files - YouTube. [ONLINE]
Available at: ​https://www.youtube.com/watch?v=Uh2ebFW8OYM​. [Accessed 28 March 2018].
YouTube. 2018. Text Files in Python || Python Tutorial || Learn Python Programming - YouTube.
[ONLINE] Available at: ​https://www.youtube.com/watch?v=4mX0uPQFLDU​. [Accessed 28 March
2018].
Severance, C., 2016. Python for Everybody. Final ed. New York, USA: Creative Commons
Attribution-NonCommercial- ShareAlike 3.0 Unported License.
5

More Related Content

What's hot (19)

PPT
file handling1
student
 
PDF
2Bytesprog2 course_2014_c1_sets
kinan keshkeh
 
PDF
Workshop programs
Kracekumar Ramaraju
 
PPT
Presentation on files
mallubenal
 
PDF
Files in c
TanujaA3
 
PDF
Php file handling in Hindi
Vipin sharma
 
PPT
Basic command ppt
Rohit Kumar
 
DOCX
Basic linux commands
Dheeraj Nambiar
 
PPTX
Php File Operations
Jamshid Hashimi
 
PPTX
Hebrew Windows Cluster 2012 in a one slide diagram
G M
 
DOCX
Zotero Part1
Samah Saber
 
PPTX
Linux Basic commands and VI Editor
shanmuga rajan
 
PDF
faastCrystal
Sachirou Inoue
 
PDF
Vi Editor
Shiwang Kalkhanda
 
PPTX
Basics of unix
Deepak Singhal
 
PDF
Filesinc 130512002619-phpapp01
Rex Joe
 
PPT
php file uploading
Purushottam Kumar
 
PPTX
File handling in c language
Harish Gyanani
 
file handling1
student
 
2Bytesprog2 course_2014_c1_sets
kinan keshkeh
 
Workshop programs
Kracekumar Ramaraju
 
Presentation on files
mallubenal
 
Files in c
TanujaA3
 
Php file handling in Hindi
Vipin sharma
 
Basic command ppt
Rohit Kumar
 
Basic linux commands
Dheeraj Nambiar
 
Php File Operations
Jamshid Hashimi
 
Hebrew Windows Cluster 2012 in a one slide diagram
G M
 
Zotero Part1
Samah Saber
 
Linux Basic commands and VI Editor
shanmuga rajan
 
faastCrystal
Sachirou Inoue
 
Basics of unix
Deepak Singhal
 
Filesinc 130512002619-phpapp01
Rex Joe
 
php file uploading
Purushottam Kumar
 
File handling in c language
Harish Gyanani
 

Similar to Python 3.x File Object Manipulation Cheatsheet (20)

PPTX
PPS PPT 2.pptx
Sandeepbhuma1
 
PPT
file_handling_in_c.ppt
yuvrajkeshri
 
PPT
Python File functions
keerthanakommera1
 
PDF
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
PPTX
File Handling Topic for tech management you know na tho kyuon puch raha hai sale
RohitKurdiya1
 
PPT
Unit5
mrecedu
 
PPTX
Programming C- File Handling , File Operation
svkarthik86
 
PPT
File handling in c
thirumalaikumar3
 
PDF
file handling.pdf
RonitVaskar2
 
PDF
File handling in Python
BMS Institute of Technology and Management
 
PPT
File handling-c
CGC Technical campus,Mohali
 
PPT
Unit5 C
arnold 7490
 
PPTX
FILES CONCEPTS IN PYTHON PROGRAMMING.pptx
shalinikarunakaran1
 
DOCX
Files let you store data on secondary storage such as a hard disk so that you...
Bern Jamie
 
PPT
file.ppt
DeveshDewangan5
 
PDF
Module 03 File Handling in C
Tushar B Kute
 
PPTX
FILE INPUT OUTPUT.pptx
ssuserd0df33
 
DOCX
File Handling in python.docx
manohar25689
 
PDF
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
sangeeta borde
 
PPTX
Python files / directories part16
Vishal Dutt
 
PPS PPT 2.pptx
Sandeepbhuma1
 
file_handling_in_c.ppt
yuvrajkeshri
 
Python File functions
keerthanakommera1
 
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
File Handling Topic for tech management you know na tho kyuon puch raha hai sale
RohitKurdiya1
 
Unit5
mrecedu
 
Programming C- File Handling , File Operation
svkarthik86
 
File handling in c
thirumalaikumar3
 
file handling.pdf
RonitVaskar2
 
Unit5 C
arnold 7490
 
FILES CONCEPTS IN PYTHON PROGRAMMING.pptx
shalinikarunakaran1
 
Files let you store data on secondary storage such as a hard disk so that you...
Bern Jamie
 
file.ppt
DeveshDewangan5
 
Module 03 File Handling in C
Tushar B Kute
 
FILE INPUT OUTPUT.pptx
ssuserd0df33
 
File Handling in python.docx
manohar25689
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
sangeeta borde
 
Python files / directories part16
Vishal Dutt
 
Ad

More from Isham Rashik (20)

PDF
Text Preprocessing - 1
Isham Rashik
 
PDF
9608 Computer Science Cambridge International AS level Pre-Release May June p...
Isham Rashik
 
PDF
Fundamentals of Cryptography - Caesar Cipher - Python
Isham Rashik
 
PDF
Python 3.x Dictionaries and Sets Cheatsheet
Isham Rashik
 
PDF
HackerRank Repeated String Problem
Isham Rashik
 
PDF
Operations Management - BSB INC - Case Study
Isham Rashik
 
PDF
Corporate Finance - Disney Sea Park Project
Isham Rashik
 
PDF
Questionnaire - Why women entrepreneurs are happier than men?
Isham Rashik
 
PDF
Human Resource Management - Different Interview Techniques
Isham Rashik
 
PDF
Android Application Development - Level 3
Isham Rashik
 
PDF
Android Application Development - Level 2
Isham Rashik
 
PDF
Android Application Development - Level 1
Isham Rashik
 
PDF
Managerial Skills Presentation - Elon Musk
Isham Rashik
 
PDF
Operations Management - Business Process Reengineering - Example
Isham Rashik
 
PPTX
Lighting Design - Theory and Calculations
Isham Rashik
 
PDF
Linear Control Hard-Disk Read/Write Controller Assignment
Isham Rashik
 
PDF
Transformers and Induction Motors
Isham Rashik
 
PDF
Three phase balanced load circuits and synchronous generators
Isham Rashik
 
PPTX
Circuit Breakers for Low Voltage Applications
Isham Rashik
 
PDF
Linux Commands - Cheat Sheet
Isham Rashik
 
Text Preprocessing - 1
Isham Rashik
 
9608 Computer Science Cambridge International AS level Pre-Release May June p...
Isham Rashik
 
Fundamentals of Cryptography - Caesar Cipher - Python
Isham Rashik
 
Python 3.x Dictionaries and Sets Cheatsheet
Isham Rashik
 
HackerRank Repeated String Problem
Isham Rashik
 
Operations Management - BSB INC - Case Study
Isham Rashik
 
Corporate Finance - Disney Sea Park Project
Isham Rashik
 
Questionnaire - Why women entrepreneurs are happier than men?
Isham Rashik
 
Human Resource Management - Different Interview Techniques
Isham Rashik
 
Android Application Development - Level 3
Isham Rashik
 
Android Application Development - Level 2
Isham Rashik
 
Android Application Development - Level 1
Isham Rashik
 
Managerial Skills Presentation - Elon Musk
Isham Rashik
 
Operations Management - Business Process Reengineering - Example
Isham Rashik
 
Lighting Design - Theory and Calculations
Isham Rashik
 
Linear Control Hard-Disk Read/Write Controller Assignment
Isham Rashik
 
Transformers and Induction Motors
Isham Rashik
 
Three phase balanced load circuits and synchronous generators
Isham Rashik
 
Circuit Breakers for Low Voltage Applications
Isham Rashik
 
Linux Commands - Cheat Sheet
Isham Rashik
 
Ad

Recently uploaded (20)

PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PPTX
ENGlish 8 lesson presentation PowerPoint.pptx
marawehsvinetshe
 
PDF
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
PDF
IMPORTANT GUIDELINES FOR M.Sc.ZOOLOGY DISSERTATION
raviralanaresh2
 
PDF
STATEMENT-BY-THE-HON.-MINISTER-FOR-HEALTH-ON-THE-COVID-19-OUTBREAK-AT-UG_revi...
nservice241
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PPTX
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
PPTX
How to Create a Customer From Website in Odoo 18.pptx
Celine George
 
PPT
Indian Contract Act 1872, Business Law #MBA #BBA #BCOM
priyasinghy107
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PPTX
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
PDF
Introduction presentation of the patentbutler tool
MIPLM
 
PDF
Council of Chalcedon Re-Examined
Smiling Lungs
 
PDF
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
PPTX
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
PPTX
Difference between write and update in odoo 18
Celine George
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PPTX
Introduction to Biochemistry & Cellular Foundations.pptx
marvinnbustamante1
 
PPTX
Introduction to Indian Writing in English
Trushali Dodiya
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
ENGlish 8 lesson presentation PowerPoint.pptx
marawehsvinetshe
 
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
IMPORTANT GUIDELINES FOR M.Sc.ZOOLOGY DISSERTATION
raviralanaresh2
 
STATEMENT-BY-THE-HON.-MINISTER-FOR-HEALTH-ON-THE-COVID-19-OUTBREAK-AT-UG_revi...
nservice241
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
How to Create a Customer From Website in Odoo 18.pptx
Celine George
 
Indian Contract Act 1872, Business Law #MBA #BBA #BCOM
priyasinghy107
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
Introduction presentation of the patentbutler tool
MIPLM
 
Council of Chalcedon Re-Examined
Smiling Lungs
 
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
Difference between write and update in odoo 18
Celine George
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
Introduction to Biochemistry & Cellular Foundations.pptx
marvinnbustamante1
 
Introduction to Indian Writing in English
Trushali Dodiya
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 

Python 3.x File Object Manipulation Cheatsheet

  • 1.       Python 3.x - File Objects Cheatsheet      1
  • 2. Reading files  ● To open a file and read: ​f = open(​'name-of-the-file.txt'​, ​'r'​) ● To open a file and write: ​f = open(​'name-of-the-file.txt'​, ​'w'​) ● To open a file and append(this is done to avoid overwriting of a file and include extra chunk of text to the file which has already been created): ​f = open(​'name-of-the-file.txt'​, ​'a'​) ● To open a file and read and write: ​f = open(​'name-of-the-file.txt'​, ​'r+'​) ● Prints the name of the file: ​print(f.name) ● Prints the mode if file is read or write mode: ​print(f.mode) ● Prints the file contents in the python interpreter or terminal/cmd: ​print(f.read) ● Reads the first line. Will read second line if this method is called again: f_contents = f.readline() print(f_contents) ● Reads each line of the .txt file and stores it in a list variable: f_contents = f.readlines() print(f_contents) ● Download the files: mbox.txt and mbox-short.txt for practice from: ​www.py4e.com/code3/mbox.txt and ​www.py4e.com/code3/mbox-short.txt ● To read each lines of the whole file in traditional way: fname = input(​'Enter the file name: '​) try​: fhand = open(fname, ​'r'​) # Reads each line in the file count = 0 for​ line ​in​ fhand: # end = '' removes extra line print(line, end=​''​) count = count + 1 fhand.close() except​ FileNotFoundError: print(​'File: '​ + fname + ​' cannot be opened.'​) # Terminates the program exit() print(​'There were'​, count, ​'subject lines in'​, fname) ● To read a line which starts with string ​'From:'​: for​ line ​in​ fhand: ​if​ line.startswith(​'From:'​): print(line, end=​''​) 2
  • 3. ● To read the whole file: fname = input(​'Enter the file name: '​) try​: fhand = open(fname, ​'r'​) text = fhand.read() fhand.close() except​ FileNotFoundError: print(​'File cannot be opened:'​, fname) exit() print(text) ● To read each line of the file and the line starting from ​'From:'​ using context manager: fname = input(​'Enter the file name: '​) try​: ​with​ open(fname, ​'r'​) ​as​ f: ​for​ line ​in​ f: ​if​ line.startswith(​'From:'​): print(line, end=​''​) except​ FileNotFoundError: print(​'File cannot be opened:'​, fname) exit() ● To read whole file using context manager: fname = input(​'Enter the file name: '​) try​: ​with​ open(fname, ​'r'​) ​as​ f: text = f.read() except​ FileNotFoundError: print(​'File cannot be opened:'​, fname) exit() print(text) ● To read specified number of characters from the file: fname = input(​'Enter the file name: '​) with​ open(fname, ​'r'​) ​as​ f: size_to_read = 10 f_contents = f.read(size_to_read) # Infinite loop for testing 3
  • 4. while​ len(f_contents) > 0: ​# To identify if we are looping through 10 ​# characters at a time use end='*' print(f_contents, end=​'*'​) Write to files  ● To make a new file and write to it: fout = open(​'out.txt'​, ​'w'​) line1 = ​"This here's the wattle, n" fout.write(line1) line2 = ​'the emblem of our land.n' fout.write(line2) ● To make a copy of the file: fname = input(​'Enter the file name: '​) with​ open(fname, ​'r'​) ​as​ rf: with​ open(fname[:-4] + ​'_copy.txt'​, ​'w'​) ​as​ wf: for​ line ​in​ rf: wf.write(line) ● To add content to an already written file such that overwriting doesn’t occur by going append mode from write mode: oceans = [​"Pacific"​, ​"Atlantic"​, ​"Indian"​, ​"Southern"​, ​"Arctic"​] with​ open(​"oceans.txt"​, ​"w"​) ​as​ f: for​ ocean ​in​ oceans: print(ocean, file=f) with​ open(​"oceans.txt"​, ​"a"​) ​as​ f: print(23*​"="​, file=f) print(​"These are the 5 oceans."​, file=f) ● To make a copy of other files such as .jpeg and .pdf, read binary and write binary mode has to be enabled: with​ open(​'file-of-your-choice.jpg'​, ​'rb'​) ​as​ rf: ​with​ open(​'file-of-your-choice_copy.jpg'​, ​'wb'​) ​as​ wf: ​for​ line ​in​ rf: wf.write(line) 4
  • 5. References  YouTube. 2018. Python Tutorial: File Objects - Reading and Writing to Files - YouTube. [ONLINE] Available at: ​https://www.youtube.com/watch?v=Uh2ebFW8OYM​. [Accessed 28 March 2018]. YouTube. 2018. Text Files in Python || Python Tutorial || Learn Python Programming - YouTube. [ONLINE] Available at: ​https://www.youtube.com/watch?v=4mX0uPQFLDU​. [Accessed 28 March 2018]. Severance, C., 2016. Python for Everybody. Final ed. New York, USA: Creative Commons Attribution-NonCommercial- ShareAlike 3.0 Unported License. 5