Learn Python 3 - Files Cheatsheet - Codecademy
Learn Python 3 - Files Cheatsheet - Codecademy
Files
Python File Object
A Python file object is created when a file is opened
with the open() function. You can associate this file
object with a variable when you open a file 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'>
with open('story.txt') as
story_object:
print(story_object.readline())
# Contents of file.json
# { 'userId': 10 }
import json
with open('file.json') as json_file:
python_dict = json.load(json_file)
print(python_dict.get('userId'))
# Prints 10
shop.write('Tomatoes,
cucumbers, celery\n')
with open('diary.txt','w') as
diary:
with open('lines.txt') as
file_object:
file_data
= file_object.readlines()
print(file_data)
outputs:
1. Learn Python.
2. Work hard.
Graduate.
3.
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 with open('companies.csv', 'w') as
data.
csvfile:
The csv.DictWriter constructor takes two arguments.
fieldnames = ['name', 'type']
The first is the open file handler that the CSV is being
writer = csv.DictWriter(csvfile,
written to. The second named parameter, fieldnames ,
fieldnames=fieldnames)
is a list of field names that the CSV is going to handle.
writer.writeheader()
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
"""
with open('mystery.txt') as
text_file:
= text_file.read()
text_data
print(text_data)
Mystery solved.
Congratulations!