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
Ad

More Related Content

What's hot (19)

file handling1
file handling1file handling1
file handling1
student
 
2Bytesprog2 course_2014_c1_sets
2Bytesprog2 course_2014_c1_sets2Bytesprog2 course_2014_c1_sets
2Bytesprog2 course_2014_c1_sets
kinan keshkeh
 
Workshop programs
Workshop programsWorkshop programs
Workshop programs
Kracekumar Ramaraju
 
Presentation on files
Presentation on filesPresentation on files
Presentation on files
mallubenal
 
File Handling in C Programming
File Handling in C ProgrammingFile Handling in C Programming
File Handling in C Programming
Bosco Technical Training Society, Don Bosco Technical School (Aff. GGSIP University, New Delhi)
 
Files in c
Files in cFiles in c
Files in c
TanujaA3
 
Php file handling in Hindi
Php file handling in Hindi Php file handling in Hindi
Php file handling in Hindi
Vipin sharma
 
Basic command ppt
Basic command pptBasic command ppt
Basic command ppt
Rohit Kumar
 
Basic linux commands
Basic linux commandsBasic linux commands
Basic linux commands
Dheeraj Nambiar
 
Php File Operations
Php File OperationsPhp File Operations
Php File Operations
Jamshid Hashimi
 
Hebrew Windows Cluster 2012 in a one slide diagram
Hebrew Windows Cluster 2012 in a one slide diagramHebrew Windows Cluster 2012 in a one slide diagram
Hebrew Windows Cluster 2012 in a one slide diagram
G M
 
Zotero Part1
Zotero Part1Zotero Part1
Zotero Part1
Samah Saber
 
Linux Basic commands and VI Editor
Linux Basic commands and VI EditorLinux Basic commands and VI Editor
Linux Basic commands and VI Editor
shanmuga rajan
 
faastCrystal
faastCrystalfaastCrystal
faastCrystal
Sachirou Inoue
 
Vi Editor
Vi EditorVi Editor
Vi Editor
Shiwang Kalkhanda
 
Basics of unix
Basics of unixBasics of unix
Basics of unix
Deepak Singhal
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
Rex Joe
 
php file uploading
php file uploadingphp file uploading
php file uploading
Purushottam Kumar
 
File handling in c language
File handling in c languageFile handling in c language
File handling in c language
Harish Gyanani
 

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

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

More from Isham Rashik (20)

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

Recently uploaded (20)

How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 

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