SlideShare ist ein Scribd-Unternehmen logo
1 von 5
Downloaden Sie, um offline zu lesen
 
 
 
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

Weitere ähnliche Inhalte

Was ist angesagt? (19)

file handling1
file handling1file handling1
file handling1
 
2Bytesprog2 course_2014_c1_sets
2Bytesprog2 course_2014_c1_sets2Bytesprog2 course_2014_c1_sets
2Bytesprog2 course_2014_c1_sets
 
Workshop programs
Workshop programsWorkshop programs
Workshop programs
 
Presentation on files
Presentation on filesPresentation on files
Presentation on files
 
File Handling in C Programming
File Handling in C ProgrammingFile Handling in C Programming
File Handling in C Programming
 
Files in c
Files in cFiles in c
Files in c
 
Php file handling in Hindi
Php file handling in Hindi Php file handling in Hindi
Php file handling in Hindi
 
Basic command ppt
Basic command pptBasic command ppt
Basic command ppt
 
Basic linux commands
Basic linux commandsBasic linux commands
Basic linux commands
 
Php File Operations
Php File OperationsPhp File Operations
Php File Operations
 
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
 
Zotero Part1
Zotero Part1Zotero Part1
Zotero Part1
 
Linux Basic commands and VI Editor
Linux Basic commands and VI EditorLinux Basic commands and VI Editor
Linux Basic commands and VI Editor
 
faastCrystal
faastCrystalfaastCrystal
faastCrystal
 
Vi Editor
Vi EditorVi Editor
Vi Editor
 
Basics of unix
Basics of unixBasics of unix
Basics of unix
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
 
php file uploading
php file uploadingphp file uploading
php file uploading
 
File handling in c language
File handling in c languageFile handling in c language
File handling in c language
 

Ähnlich wie Python 3.x File Object Manipulation Cheatsheet

file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.pptyuvrajkeshri
 
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 saleRohitKurdiya1
 
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 CTushar B Kute
 
FILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxFILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxssuserd0df33
 
File Handling in python.docx
File Handling in python.docxFile Handling in python.docx
File Handling in python.docxmanohar25689
 
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.pdfsangeeta borde
 
Python files / directories part16
Python files / directories  part16Python files / directories  part16
Python files / directories part16Vishal Dutt
 
File handling in c
File handling in cFile handling in c
File handling in caakanksha s
 
File Handling in C Programming
File Handling in C ProgrammingFile Handling in C Programming
File Handling in C ProgrammingRavindraSalunke3
 

Ähnlich wie Python 3.x File Object Manipulation Cheatsheet (20)

PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
Python File functions
Python File functionsPython File functions
Python File functions
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
 
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
 
Unit5
Unit5Unit5
Unit5
 
File handling in c
File  handling in cFile  handling in c
File handling in c
 
file handling.pdf
file handling.pdffile handling.pdf
file handling.pdf
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
File handling-c
File handling-cFile handling-c
File handling-c
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
 
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...
 
file.ppt
file.pptfile.ppt
file.ppt
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in C
 
FILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxFILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptx
 
File Handling in python.docx
File Handling in python.docxFile Handling in python.docx
File Handling in python.docx
 
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
 
Python files / directories part16
Python files / directories  part16Python files / directories  part16
Python files / directories part16
 
File handling in c
File handling in cFile handling in c
File handling in c
 
File Handling in C Programming
File Handling in C ProgrammingFile Handling in C Programming
File Handling in C Programming
 

Mehr von Isham Rashik

Text Preprocessing - 1
Text Preprocessing - 1Text Preprocessing - 1
Text Preprocessing - 1Isham 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 CheatsheetIsham Rashik
 
HackerRank Repeated String Problem
HackerRank Repeated String ProblemHackerRank Repeated String Problem
HackerRank Repeated String ProblemIsham Rashik
 
Operations Management - BSB INC - Case Study
Operations Management - BSB INC - Case StudyOperations Management - BSB INC - Case Study
Operations Management - BSB INC - Case StudyIsham Rashik
 
Corporate Finance - Disney Sea Park Project
Corporate Finance - Disney Sea Park ProjectCorporate Finance - Disney Sea Park Project
Corporate Finance - Disney Sea Park ProjectIsham 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 TechniquesIsham Rashik
 
Android Application Development - Level 3
Android Application Development - Level 3Android Application Development - Level 3
Android Application Development - Level 3Isham Rashik
 
Android Application Development - Level 2
Android Application Development - Level 2Android Application Development - Level 2
Android Application Development - Level 2Isham Rashik
 
Android Application Development - Level 1
Android Application Development - Level 1Android Application Development - Level 1
Android Application Development - Level 1Isham Rashik
 
Managerial Skills Presentation - Elon Musk
Managerial Skills Presentation - Elon MuskManagerial Skills Presentation - Elon Musk
Managerial Skills Presentation - Elon MuskIsham Rashik
 
Operations Management - Business Process Reengineering - Example
Operations Management - Business Process Reengineering - ExampleOperations Management - Business Process Reengineering - Example
Operations Management - Business Process Reengineering - ExampleIsham Rashik
 
Lighting Design - Theory and Calculations
Lighting Design - Theory and CalculationsLighting Design - Theory and Calculations
Lighting Design - Theory and CalculationsIsham 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 AssignmentIsham Rashik
 
Transformers and Induction Motors
Transformers and Induction MotorsTransformers and Induction Motors
Transformers and Induction MotorsIsham 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 generatorsIsham Rashik
 
Circuit Breakers for Low Voltage Applications
Circuit Breakers for Low Voltage ApplicationsCircuit Breakers for Low Voltage Applications
Circuit Breakers for Low Voltage ApplicationsIsham Rashik
 
Linux Commands - Cheat Sheet
Linux Commands - Cheat Sheet Linux Commands - Cheat Sheet
Linux Commands - Cheat Sheet Isham Rashik
 

Mehr von Isham Rashik (20)

Text Preprocessing - 1
Text Preprocessing - 1Text Preprocessing - 1
Text Preprocessing - 1
 
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...
 
Fundamentals of Cryptography - Caesar Cipher - Python
Fundamentals of Cryptography - Caesar Cipher - Python Fundamentals of Cryptography - Caesar Cipher - Python
Fundamentals of Cryptography - Caesar Cipher - Python
 
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
 
HackerRank Repeated String Problem
HackerRank Repeated String ProblemHackerRank Repeated String Problem
HackerRank Repeated String Problem
 
Operations Management - BSB INC - Case Study
Operations Management - BSB INC - Case StudyOperations Management - BSB INC - Case Study
Operations Management - BSB INC - Case Study
 
Corporate Finance - Disney Sea Park Project
Corporate Finance - Disney Sea Park ProjectCorporate Finance - Disney Sea Park Project
Corporate Finance - Disney Sea Park Project
 
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?
 
Human Resource Management - Different Interview Techniques
Human Resource Management - Different Interview TechniquesHuman Resource Management - Different Interview Techniques
Human Resource Management - Different Interview Techniques
 
Android Application Development - Level 3
Android Application Development - Level 3Android Application Development - Level 3
Android Application Development - Level 3
 
Android Application Development - Level 2
Android Application Development - Level 2Android Application Development - Level 2
Android Application Development - Level 2
 
Android Application Development - Level 1
Android Application Development - Level 1Android Application Development - Level 1
Android Application Development - Level 1
 
Managerial Skills Presentation - Elon Musk
Managerial Skills Presentation - Elon MuskManagerial Skills Presentation - Elon Musk
Managerial Skills Presentation - Elon Musk
 
Operations Management - Business Process Reengineering - Example
Operations Management - Business Process Reengineering - ExampleOperations Management - Business Process Reengineering - Example
Operations Management - Business Process Reengineering - Example
 
Lighting Design - Theory and Calculations
Lighting Design - Theory and CalculationsLighting Design - Theory and Calculations
Lighting Design - Theory and Calculations
 
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
 
Transformers and Induction Motors
Transformers and Induction MotorsTransformers and Induction Motors
Transformers and Induction Motors
 
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
 
Circuit Breakers for Low Voltage Applications
Circuit Breakers for Low Voltage ApplicationsCircuit Breakers for Low Voltage Applications
Circuit Breakers for Low Voltage Applications
 
Linux Commands - Cheat Sheet
Linux Commands - Cheat Sheet Linux Commands - Cheat Sheet
Linux Commands - Cheat Sheet
 

Kürzlich hochgeladen

Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 

Kürzlich hochgeladen (20)

Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 

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