Files Cheatsheet
Files Cheatsheet
Files
Python File Object
A Python le object is created when a le is opened with
the open() function. You can associate this le object
with a variable when you open a le using the with and
as keywords. For example:
with open('somefile.txt') as
file_object:
print(file_object)
<_io.TextIOWrapper name='somefile.txt'
mode='r' encoding='UTF-8'>
Mystery solved.
Congratulations!
/
Python Readlines Method
Instead of reading the entire content of a le, you can
read a single line at a time. Instead of .read() which
returns a string, call .readlines() to return a list of
strings, each representing an individual line in the le.
Calling this code:
outputs:
1. Learn Python.
2. Work hard.
3. Graduate.
with open('story.txt') as
story_object:
print(story_object.readline())
/
Python Write To File
By default, a le when opened with open() is only for
reading. A second argument 'r' is passed to it by
default. To write to a le, rst open the le with write
permission via the 'w' argument. Then use the
.write() method to write to the le. If the le already
exists, all prior content will be overwritten.
/
Class csv.DictWriter
In Python, the csv module implements classes to read
and write tabular data in CSV format. It has a class # An example of csv.DictWriter
DictWriter which operates like a regular writer but import csv
maps a dictionary onto output rows. The keys of the
dictionary are column names while values are actual data. with open('companies.csv', 'w') as csvfile:
The csv.DictWriter constructor takes two fieldnames = ['name', 'type']
arguments. The rst is the open le handler that the CSV writer = csv.DictWriter(csvfile,
is being written to. The second named parameter, fieldnames=fieldnames)
fieldnames , is a list of eld names that the CSV is writer.writeheader()
going to handle. writer.writerow({'name': 'Codecademy',
'type': 'Learning'})
writer.writerow({'name': 'Google', 'type':
'Search'})
"""
After running the above code, companies.csv
will contain the following information:
name,type
Codecademy,Learning
Google,Search
"""