Testando Funções Do Python No Google Colab

Fazer download em pdf ou txt
Fazer download em pdf ou txt
Você está na página 1de 59

1

July 20, 2021

Aluno: Augusto Pereira Salgado nº 11311ECP016

[7]: message = 'Hello World'


print(message)

Hello world

[8]: message = 'Hello World'


print(len(message))

11

[9]: message = 'Hello World'


print(message[0:5])

Hello

[12]: message = 'Hello World'


print(message.lower())

hello world

[13]: message = 'Hello World'


print(message.upper())

HELLO WORLD

[15]: message = 'Hello World'


print(message.count('l'))

[16]: message = 'Hello World'


print(message.find('World'))

[18]: message = 'Hello World'


message.replace('World',"Universe")

[18]: 'Hello Universe'

1
[23]: greeting = 'Hello'
name = 'Augusto'
message = greeting + ', ' + name
print(message)

Hello, Augusto

[24]: greeting = 'Hello'


name = 'Augusto'
message ='{}, {}. Welcome! '.format(greeting,name)
print(message)

`Hello, Augusto. Welcome!

[27]: greeting = 'Hello'


name = 'Augusto'
message = f'{greeting}, {name.upper()}. Welcome!'
print(message)

Hello, AUGUSTO. Welcome!

[28]: print(help(str.lower))

Help on method_descriptor:

lower(self, /)
Return a copy of the string converted to lowercase.

None

[ ]:

2
2

July 20, 2021

[ ]: #Operadores:
num_1 = '100'
num_2 = '200'

[49]: # Adição:
print(3 + 2)

[32]: # Subtração:
print(3 - 2)

[33]: # Multiplicação:
print(3 * 2)

[34]: # Divisão:
print(3 / 2)

1.5

[35]: # Parte inteira:


print(3 // 2)

[36]: # Exponente:
print(3 ** 2)

[37]: # Modulo:
print(3 % 2)

[38]: # Comparações:
# igualdade:

1
print(3 == 2)

False

[39]: #desigualdade:
print(3 != 2)

True

[40]: # maior que:


print(3 > 2)

True

[41]: # menor que:


print( 3 < 2)

False

[42]: # maior ou igual:


print(3 >= 2)

True

[43]: # menor ou igual:


print(3 <= 2)

False

[ ]:

[ ]:

2
3

July 20, 2021

[3]: courses = ['History', 'Math', 'Physics', 'CompSci']


print(courses[2:])

['Physics', 'CompSci']

[7]: courses = ['History', 'Math', 'Physics', 'CompSci']


courses.append('Art')
print(courses)

['History', 'Math', 'Physics', 'CompSci', 'Art']

[8]: courses = ['History', 'Math', 'Physics', 'CompSci']


courses.insert(0,'Art')
print(courses)

['Art', 'History', 'Math', 'Physics', 'CompSci']

[9]: courses = ['History', 'Math', 'Physics', 'CompSci']


courses_2 = ['Art', 'Education']
courses.insert(0,courses_2)
print(courses)

[['Art', 'Education'], 'History', 'Math', 'Physics', 'CompSci']

[10]: courses = ['History', 'Math', 'Physics', 'CompSci']


courses_2 = ['Art', 'Education']
courses.extend(courses_2)
print(courses)

['History', 'Math', 'Physics', 'CompSci', 'Art', 'Education']

[11]: courses = ['History', 'Math', 'Physics', 'CompSci']


courses_2 = ['Art', 'Education']
courses.append(courses_2)
print(courses)

['History', 'Math', 'Physics', 'CompSci', ['Art', 'Education']]

[12]: courses = ['History', 'Math', 'Physics', 'CompSci']

courses.remove('Math')

1
print(courses)

['History', 'Physics', 'CompSci']

[13]: courses = ['History', 'Math', 'Physics', 'CompSci']


#remove o ultimo item adicionado
courses.pop()
print(courses)

['History', 'Math', 'Physics']

[14]: courses = ['History', 'Math', 'Physics', 'CompSci']

courses.reverse()
print(courses)

['CompSci', 'Physics', 'Math', 'History']

[16]: courses = ['History', 'Math', 'Physics', 'CompSci']


nums = [1, 5, 2, 4, 3]

nums.sort(reverse= True)
courses.sort(reverse= True)
print(courses)
print(nums)

['Physics', 'Math', 'History', 'CompSci']


[5, 4, 3, 2, 1]

[18]: courses = ['History', 'Math', 'Physics', 'CompSci']

sorted_courses = sorted(courses)
print(sorted_courses)

['CompSci', 'History', 'Math', 'Physics']

[19]: courses = ['History', 'Math', 'Physics', 'CompSci']


print(courses.index('CompSci'))

[20]: courses = ['History', 'Math', 'Physics', 'CompSci']


print('Math'in courses)

True

[23]: courses = ['History', 'Math', 'Physics', 'CompSci']


for item in courses:
print(item)

2
History
Math
Physics
CompSci

[24]: courses = ['History', 'Math', 'Physics', 'CompSci']


for index, course in enumerate(courses):
print(index, course)

0 History
1 Math
2 Physics
3 CompSci

[38]: list_1 = ['History', 'Math', 'Physics', 'CompSci']


list_2 = list_1

list_1[0] = 'Art'
print(list_1)
print(list_2)

['Art', 'Math', 'Physics', 'CompSci']


['Art', 'Math', 'Physics', 'CompSci']

[44]: cs_courses = {'History', 'Math', 'Physics', 'CompSci', 'Math' }


print(cs_courses)

{'History', 'CompSci', 'Physics', 'Math'}

[46]: cs_courses = {'History', 'Math', 'Physics', 'CompSci', 'Math' }


art_courses = {'History','Math','Art','Design'}
print(cs_courses.difference(art_courses))

{'CompSci', 'Physics'}

[47]: cs_courses = {'History', 'Math', 'Physics', 'CompSci', 'Math' }


art_courses = {'History','Math','Art','Design'}
print(cs_courses.union(art_courses))

{'History', 'CompSci', 'Design', 'Physics', 'Math', 'Art'}

[ ]:

3
4

July 20, 2021

[1]: student = {'name': 'Augusto', 'age': 26, 'courses': ['Math', 'CompSci']}

print(student['courses'])

['Math', 'CompSci']

[2]: student = {'name': 'Augusto', 'age': 26, 'courses': ['Math', 'CompSci']}

print(student.get('name'))

Augusto

[3]: student = {'name': 'Augusto', 'age': 26, 'courses': ['Math', 'CompSci']}

print(student.get('phone','not found'))

not found

[5]: student = {'name': 'Augusto', 'age': 26, 'courses': ['Math', 'CompSci']}

student.update({'name': 'Augusto Pereira', 'age': 27, 'phone':'3232-3232'})


print(student)

{'name': 'Augusto Pereira', 'age': 27, 'courses': ['Math', 'CompSci'], 'phone':


'3232-3232'}

[8]: student = {'name': 'Augusto', 'age': 26, 'courses': ['Math', 'CompSci']}

del student['age']
print(student)

{'name': 'Augusto', 'courses': ['Math', 'CompSci']}

[9]: student = {'name': 'Augusto', 'age': 26, 'courses': ['Math', 'CompSci']}

age = student.pop('age')
print(student)

{'name': 'Augusto', 'courses': ['Math', 'CompSci']}

1
[10]: student = {'name': 'Augusto', 'age': 26, 'courses': ['Math', 'CompSci']}
for key, value in student.items():
print(key, value)

name Augusto
age 26
courses ['Math', 'CompSci']

[ ]:

2
5

July 20, 2021

[1]: language = 'Python'

if language =='Python':
print('Conditional was True')

Conditional was True

[2]: language = 'Java'

if language =='Python':
print('Conditional was True')
else:
print('no match')

no match

[4]: language = 'Java'

if language =='Python':
print('Conditional was True')
elif language =='Java':
print('language was java')
else:
print('no match')

language was java

[6]: language = 'Java'

if language =='Python':
print('Conditional was True')
elif language =='Java':
print('language was java')
elif language =='Javascript':
print('language was javascript')
else:
print('no match')

language was java

1
[9]: user = 'Admin'
logged_in = True
if user == 'Admin' and logged_in:
print('Admin Page')
else:
print('Bad Creds')

Admin Page

[11]: user = 'Admin'


logged_in = False
if not logged_in:
print('Please log in')
else:
print('Welcome')

Please log in

[12]: a = [1, 2, 3]
b = [1, 2, 3]

print(a == b)

True

[13]: a = [1, 2, 3]
b = [1, 2, 3]

print(a is b)

False

[14]: a = [1, 2, 3]
b = a

print(id(a))
print(id(b))

print(a is b)

1773087071744
1773087071744
True

[15]: a = [1, 2, 3]
b = a

2
print(id(a))
print(id(b))

print(id(a)==id(b))

1773087063552
1773087063552
True

[16]: # valores falsos:


# False
# None
# Zero ou qualquer tipo numerico
# sequencias vazias '', (), [].
# mapeamento vazio {}.

condition = False

if condition:
print('Evaluated to True')
else:
print('Evaluated to False')

Evaluated to False

[ ]:

3
6

July 20, 2021

[3]: nums = [1,2,3,4,5]

for num in nums:


if num==3:
print('Found!')
break
print(num)

1
2
Found!

[4]: nums = [1,2,3,4,5]

for num in nums:


if num==3:
print('Found!')
continue
print(num)

1
2
Found!
4
5

[5]: nums = [1,2,3,4,5]

for num in nums:


for letter in 'abc':
print(num,letter)

1 a
1 b
1 c
2 a
2 b
2 c
3 a

1
3 b
3 c
4 a
4 b
4 c
5 a
5 b
5 c

[6]: for i in range(1,11):


print(i)

1
2
3
4
5
6
7
8
9
10

[10]: x = 0
while x < 10:
print(x)
x += 1

0
1
2
3
4
5
6
7
8
9

[11]: x = 0
while x < 10:
if x==5:
break
print(x)
x += 1

0
1
2

2
3
4

[ ]:

3
7

July 20, 2021

[1]: def hello_func():


pass
print(hello_func)

<function hello_func at 0x00000185B34803A0>

[3]: def hello_func():


print('hello function!')
hello_func()

hello function!

[4]: def hello_func():


print('hello function!')
hello_func()
hello_func()
hello_func()
hello_func()

hello function!
hello function!
hello function!
hello function!

[5]: def hello_func():


return 'hello function!'

print(hello_func().upper())

HELLO FUNCTION!

[7]: def hello_func(greeting):


return '{} Function.'.format(greeting)

print(hello_func('Hi'))

Hi Function.

[10]: def hello_func(greeting, name= 'You'):


return '{}, {}' .format(greeting, name)

1
print(hello_func('Hi'))

Hi, You

[11]: def hello_func(greeting, name= 'You'):


return '{}, {}' .format(greeting, name)

print(hello_func('Hi', name='Augusto'))

Hi, Augusto

[12]: def student_info(*args, **kwargs):


print(args)
print(kwargs)
student_info('Math', 'Art', name='Augusto', age=26)

('Math', 'Art')
{'name': 'Augusto', 'age': 26}

[14]: def student_info(*args, **kwargs):


print(args)
print(kwargs)

courses = ['Math','Art']
info = {'name':'Augusto','age':22}
student_info(*courses, **info)

('Math', 'Art')
{'name': 'Augusto', 'age': 22}

[18]: # Numero de dias em cada mes


month_days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

def is_leap(year):
"""Return True for leap years, False for non-leap years."""

return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

def days_in_month(year, month):


"""Return number of days in that month in that year."""

if not 1 <= month <= 12:


return 'Invalid Month'

if month == 2 and is_leap(year):


return 29

2
return month_days[month]

print(is_leap(2021))

False

[19]: # Numero de dias em cada mes


month_days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

def is_leap(year):
"""Return True for leap years, False for non-leap years."""

return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

def days_in_month(year, month):


"""Return number of days in that month in that year."""

if not 1 <= month <= 12:


return 'Invalid Month'

if month == 2 and is_leap(year):


return 29

return month_days[month]

print(days_in_month(2021,2))

28

[ ]:

3
9

July 20, 2021

[1]: import os

os.chdir('/Users/augus/Desktop/')

print(os.getcwd())

C:\Users\augus\Desktop

[2]: import os

os.chdir('/Users/augus/Desktop/')

print(os.listdir())

['cant.txt', 'Curriculo para estagio Augusto Pereira Salgado.docx', 'Curriculo


para estagio Augusto Pereira Salgado.pdf', 'Design colaborativo.docx',
'desktop.ini', 'Entrevistas com clientes sobre o aplicativo Vitta.pdf',
'Entrevistas com clientes sobre os produtos desenvolvidos do aplicativo
Vitta.docx', 'It Takes Two.lnk', 'memorial do sistema desenvolvido do aplicativo
Vitta.pdf', 'memorial do sistema desenvolvido.docx', 'Primeira versão no
figma.docx', 'Primeira versão no figma.pdf', 'Projeto Eletrônico - Augusto
Pereira Salgado 11311ECP016.docx', 'Projeto Eletrônico - Augusto Pereira Salgado
11311ECP016.pdf', 'Proposta de aplicativo Augusto Pereira Salgado
11311ECP016.docx', 'Proposta de aplicativo Augusto Pereira Salgado
11311ECP016.pdf', 'venv.txt', 'Visual Studio Code.lnk', 'W10 Digital Activation
1.3.9.zip', 'Zelda Ocarina of Time 4K - Atalho.lnk']

[6]: import os

os.chdir('/Users/augus/Desktop/')

#os.mkdir('OS-Demo-2/Sub-Dir-1')
os.makedirs('OS-Demo-2/Sub-Dir-1')

print(os.listdir())

['cant.txt', 'Curriculo para estagio Augusto Pereira Salgado.docx', 'Curriculo


para estagio Augusto Pereira Salgado.pdf', 'Design colaborativo.docx',
'desktop.ini', 'Entrevistas com clientes sobre o aplicativo Vitta.pdf',

1
'Entrevistas com clientes sobre os produtos desenvolvidos do aplicativo
Vitta.docx', 'It Takes Two.lnk', 'memorial do sistema desenvolvido do aplicativo
Vitta.pdf', 'memorial do sistema desenvolvido.docx', 'OS-Demo-2', 'Primeira
versão no figma.docx', 'Primeira versão no figma.pdf', 'Projeto Eletrônico -
Augusto Pereira Salgado 11311ECP016.docx', 'Projeto Eletrônico - Augusto Pereira
Salgado 11311ECP016.pdf', 'Proposta de aplicativo Augusto Pereira Salgado
11311ECP016.docx', 'Proposta de aplicativo Augusto Pereira Salgado
11311ECP016.pdf', 'venv.txt', 'Visual Studio Code.lnk', 'W10 Digital Activation
1.3.9.zip', 'Zelda Ocarina of Time 4K - Atalho.lnk']

[7]: import os

os.chdir('/Users/augus/Desktop/')

os.removedirs('OS-Demo-2/Sub-Dir-1')

print(os.listdir())

['cant.txt', 'Curriculo para estagio Augusto Pereira Salgado.docx', 'Curriculo


para estagio Augusto Pereira Salgado.pdf', 'Design colaborativo.docx',
'desktop.ini', 'Entrevistas com clientes sobre o aplicativo Vitta.pdf',
'Entrevistas com clientes sobre os produtos desenvolvidos do aplicativo
Vitta.docx', 'It Takes Two.lnk', 'memorial do sistema desenvolvido do aplicativo
Vitta.pdf', 'memorial do sistema desenvolvido.docx', 'Primeira versão no
figma.docx', 'Primeira versão no figma.pdf', 'Projeto Eletrônico - Augusto
Pereira Salgado 11311ECP016.docx', 'Projeto Eletrônico - Augusto Pereira Salgado
11311ECP016.pdf', 'Proposta de aplicativo Augusto Pereira Salgado
11311ECP016.docx', 'Proposta de aplicativo Augusto Pereira Salgado
11311ECP016.pdf', 'venv.txt', 'Visual Studio Code.lnk', 'W10 Digital Activation
1.3.9.zip', 'Zelda Ocarina of Time 4K - Atalho.lnk']

[8]: import os

os.chdir('/Users/augus/Desktop/')

os.rename('text.txt','demo.txt')

print(os.listdir())

['cant.txt', 'Curriculo para estagio Augusto Pereira Salgado.docx', 'Curriculo


para estagio Augusto Pereira Salgado.pdf', 'demo.txt', 'Design
colaborativo.docx', 'desktop.ini', 'Entrevistas com clientes sobre o aplicativo
Vitta.pdf', 'Entrevistas com clientes sobre os produtos desenvolvidos do
aplicativo Vitta.docx', 'It Takes Two.lnk', 'memorial do sistema desenvolvido do
aplicativo Vitta.pdf', 'memorial do sistema desenvolvido.docx', 'Primeira versão
no figma.docx', 'Primeira versão no figma.pdf', 'Projeto Eletrônico - Augusto
Pereira Salgado 11311ECP016.docx', 'Projeto Eletrônico - Augusto Pereira Salgado

2
11311ECP016.pdf', 'Proposta de aplicativo Augusto Pereira Salgado
11311ECP016.docx', 'Proposta de aplicativo Augusto Pereira Salgado
11311ECP016.pdf', 'venv.txt', 'Visual Studio Code.lnk', 'W10 Digital Activation
1.3.9.zip', 'Zelda Ocarina of Time 4K - Atalho.lnk']

[13]: import os

os.chdir('/Users/augus/Desktop/')

os.stat('demo.txt')

#print(os.listdir())

[13]: os.stat_result(st_mode=33206, st_ino=1970324838039550, st_dev=1090086632,


st_nlink=1, st_uid=0, st_gid=0, st_size=11, st_atime=1626822014,
st_mtime=1626822014, st_ctime=1626821876)

[12]: import os

os.chdir('/Users/augus/Desktop/')

print(os.stat('demo.txt').st_size)

#print(os.listdir())

11

[14]: import os

os.chdir('/Users/augus/Desktop/')

print(os.stat('demo.txt').st_mtime)

#print(os.listdir())

1626822014.4637685

[17]: import os
from datetime import datetime

os.chdir('/Users/augus/Desktop/')

mod_time = os.stat('demo.txt').st_mtime
print(datetime.fromtimestamp(mod_time))

3
#print(os.listdir())

2021-07-20 20:00:14.463768

[20]: import os
from datetime import datetime

os.chdir('/Users/augus/Desktop/')

for dirpath, dirnames, filenames in os.walk('/Users/augus/Desktop/'):


print('Current Path:', dirpath)
print('Directories:', dirnames)
print('Files', filenames)
print()

Current Path: /Users/augus/Desktop/


Directories: []
Files ['cant.txt', 'Curriculo para estagio Augusto Pereira Salgado.docx',
'Curriculo para estagio Augusto Pereira Salgado.pdf', 'demo.txt', 'Design
colaborativo.docx', 'desktop.ini', 'Entrevistas com clientes sobre o aplicativo
Vitta.pdf', 'Entrevistas com clientes sobre os produtos desenvolvidos do
aplicativo Vitta.docx', 'It Takes Two.lnk', 'memorial do sistema desenvolvido do
aplicativo Vitta.pdf', 'memorial do sistema desenvolvido.docx', 'Primeira versão
no figma.docx', 'Primeira versão no figma.pdf', 'Projeto Eletrônico - Augusto
Pereira Salgado 11311ECP016.docx', 'Projeto Eletrônico - Augusto Pereira Salgado
11311ECP016.pdf', 'Proposta de aplicativo Augusto Pereira Salgado
11311ECP016.docx', 'Proposta de aplicativo Augusto Pereira Salgado
11311ECP016.pdf', 'venv.txt', 'Visual Studio Code.lnk', 'W10 Digital Activation
1.3.9.zip', 'Zelda Ocarina of Time 4K - Atalho.lnk']

[29]: import os
from datetime import datetime

os.chdir('/Users/augus/Desktop/')

print(os.environ.get('HOME'))

None

[30]: import os
from datetime import datetime

os.chdir('/Users/augus/Desktop/')

print(os.path.dirname('/tmp/test.txt'))

/tmp

4
[31]: import os
from datetime import datetime

os.chdir('/Users/augus/Desktop/')

print(os.path.split('/tmp/test.txt'))

('/tmp', 'test.txt')

[32]: import os
from datetime import datetime

os.chdir('/Users/augus/Desktop/')

print(os.path.exists('/tmp/test.txt'))

False

[33]: import os
from datetime import datetime

os.chdir('/Users/augus/Desktop/')

print(os.path.isfile('/tmp/test.txt'))

False

[34]: import os
from datetime import datetime

os.chdir('/Users/augus/Desktop/')

print(os.path.splitext('/tmp/test.txt'))

('/tmp/test', '.txt')

[35]: import os
from datetime import datetime

os.chdir('/Users/augus/Desktop/')

print(dir(os.path))

['__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__',


'__name__', '__package__', '__spec__', '_abspath_fallback', '_get_bothseps',
'_getfinalpathname', '_getfinalpathname_nonstrict', '_getfullpathname',
'_getvolumepathname', '_nt_readlink', '_readlink_deep', 'abspath', 'altsep',
'basename', 'commonpath', 'commonprefix', 'curdir', 'defpath', 'devnull',
'dirname', 'exists', 'expanduser', 'expandvars', 'extsep', 'genericpath',
'getatime', 'getctime', 'getmtime', 'getsize', 'isabs', 'isdir', 'isfile',

5
'islink', 'ismount', 'join', 'lexists', 'normcase', 'normpath', 'os', 'pardir',
'pathsep', 'realpath', 'relpath', 'samefile', 'sameopenfile', 'samestat', 'sep',
'split', 'splitdrive', 'splitext', 'stat', 'supports_unicode_filenames', 'sys']

[ ]:

6
10

July 24, 2021

[2]: f= open('test.txt', 'r')


print(f.name)

test.txt

[3]: f= open('test.txt', 'r')


print(f.mode)

f.close()

[4]: with open('test.txt', 'r') as f:


pass
print(f.closed)

True

[5]: with open('test.txt', 'r') as f:


f_contents = f.read()

print(f_contents)

1) This is a test file


2) With multiple lines of data…
3) Third line
4) Fourth line
5) Fifth line
6) Sixth line
7) Seventh line
8) Eighth line
9) Ninth line
10) Tenth line

[6]: with open('test.txt', 'r') as f:


f_contents = f.readlines()

print(f_contents)

1
['1) This is a test file\n', '2) With multiple lines of data…\n', '3) Third
line\n', '4) Fourth line\n', '5) Fifth line\n', '6) Sixth line\n', '7) Seventh
line\n', '8) Eighth line\n', '9) Ninth line\n', '10) Tenth line']

[9]: with open('test.txt', 'r') as f:


f_contents = f.readline()

print(f_contents, end='')
f_contents = f.readline()

print(f_contents, end='')

1) This is a test file


2) With multiple lines of data…

[10]: with open('test.txt', 'r') as f:


for line in f:
print(line, end='')

1) This is a test file


2) With multiple lines of data…
3) Third line
4) Fourth line
5) Fifth line
6) Sixth line
7) Seventh line
8) Eighth line
9) Ninth line
10) Tenth line

[11]: with open('test.txt', 'r') as f:


f_contents = f.read(100)

print(f_contents, end='')

1) This is a test file


2) With multiple lines of data…
3) Third line
4) Fourth line
5) Fifth line

[12]: with open('test.txt', 'r') as f:


size_toread = 100
f_contents = f.read(size_toread)

print(f_contents, end='')

1) This is a test file


2) With multiple lines of data…
3) Third line

2
4) Fourth line
5) Fifth line

[14]: with open('test.txt', 'r') as f:


size_toread = 100
f_contents = f.read(size_toread)

while len(f_contents) > 0:


print(f_contents, end='')
f_contents = f.read(size_toread)

1) This is a test file


2) With multiple lines of data…
3) Third line
4) Fourth line
5) Fifth line
6) Sixth line
7) Seventh line
8) Eighth line
9) Ninth line
10) Tenth line

[15]: with open('test.txt', 'r') as f:


size_toread = 10
f_contents = f.read(size_toread)

while len(f_contents) > 0:


print(f_contents, end='')
f_contents = f.read(size_toread)

1) This is a test file


2) With multiple lines of data…
3) Third line
4) Fourth line
5) Fifth line
6) Sixth line
7) Seventh line
8) Eighth line
9) Ninth line
10) Tenth line

[16]: with open('test.txt', 'r') as f:


size_toread = 10
f_contents = f.read(size_toread)

print(f.tell())

10

3
[18]: with open('test.txt', 'w') as f:
f.write('Test')

[19]: with open('test2.txt', 'w') as f:


pass

[20]: with open('test2.txt', 'w') as f:


f.write('Test')

[21]: with open('test2.txt', 'r') as f:


f_contents = f.read()

print(f_contents)

Test

[22]: with open('test2.txt', 'w') as f:


f.write('Test')
f.seek(0)
f.write('R')

[23]: with open('test2.txt', 'r') as f:


f_contents = f.read()

print(f_contents)

Rest

[27]: with open('test.txt', 'r') as rf:


with open('test_copy.txt', 'w') as wf:
for line in rf:
wf.write(line)

[28]: with open('test_copy.txt', 'r') as f:


f_contents = f.read()

print(f_contents)

1) This is a test file


2) With multiple lines of data…
3) Third line
4) Fourth line
5) Fifth line
6) Sixth line
7) Seventh line
8) Eighth line
9) Ninth line
10) Tenth line

4
11

July 20, 2021

[1]: import os

os.chdir('/Users/augus/Desktop/teste/')

for f in os.listdir():
print(f)

1.jpg
2.jpg
3.gif
4.jpg
5.jpg
chá.png
Sem título.jpg
voltar.png

[6]: import os

os.chdir('/Users/augus/Desktop/teste/')

for f in os.listdir():
print(os.path.splitext(f))

('1', '.jpg')
('2', '.jpg')
('3', '.gif')
('4', '.jpg')
('5', '.jpg')
('chá', '.png')
('Sem título', '.jpg')
('voltar', '.png')

[8]: import os

os.chdir('/Users/augus/Desktop/teste/')

for f in os.listdir():
file_name, file_ext = os.path.splitext(f)
print(file_name)

1
1
2
3
4
5
chá
Sem título
voltar

[10]: import os

os.chdir('/Users/augus/Desktop/teste/')

for f in os.listdir():
file_name, file_ext = os.path.splitext(f)
print(file_name.split('-'))

['1']
['2']
['3']
['4']
['5']
['chá']
['Sem título']
['voltar']

[23]: import os

os.chdir('/Users/augus/Desktop/teste/')

for f in os.listdir():
file_name, file_ext = os.path.splitext(f)
f_title = file_name.split('-')
f_course = file_name.split('-')
f_number = file_name.split('-')

print('{}-{}-{}{}'.format(f_number, f_course, f_title, file_ext))

['1']-['1']-['1'].jpg
['2']-['2']-['2'].jpg
['3']-['3']-['3'].gif
['4']-['4']-['4'].jpg
['5']-['5']-['5'].jpg
['chá']-['chá']-['chá'].png
['Sem título']-['Sem título']-['Sem título'].jpg
['voltar']-['voltar']-['voltar'].png

2
[32]: import os

os.chdir('/Users/augus/Desktop/teste/')

for f in os.listdir():
file_name, file_ext = os.path.splitext(f)
f_title = file_name.split('-')
f_course = file_name.split('-')
f_number = file_name.split('-')

print('{}-{}-{}{}'.format(f_number, f_course, f_title, file_ext))

#new_name = '{}-{}{}'.format(file_number, file_title, file_ext)

#os.rename(fn, new_name)

['1']-['1']-['1'].jpg
['2']-['2']-['2'].jpg
['3']-['3']-['3'].gif
['4']-['4']-['4'].jpg
['5']-['5']-['5'].jpg
['chá']-['chá']-['chá'].png
['Sem título']-['Sem título']-['Sem título'].jpg
['voltar']-['voltar']-['voltar'].png

[ ]:

3
13

July 20, 2021

[23]: import csv

with open('names.csv', 'r') as csv_file:


csv_reader = csv.reader(csv_file)

for line in csv_reader:


print(line)

['first_name', 'last_name', 'email']


['John', 'Doe', '[email protected]']
['Mary', 'Smith-Robinson', '[email protected]']
['Dave', 'Smith', '[email protected]']
['Jane', 'Stuart', '[email protected]']
['Tom', 'Wright', '[email protected]']
['Steve', 'Robinson', '[email protected]']
['Nicole', 'Jacobs', '[email protected]']
['Jane', 'Wright', '[email protected]']
['Jane', 'Doe', '[email protected]']
['Kurt', 'Wright', '[email protected]']
['Kurt', 'Robinson', '[email protected]']
['Jane', 'Jenkins', '[email protected]']
['Neil', 'Robinson', '[email protected]']
['Tom', 'Patterson', '[email protected]']
['Sam', 'Jenkins', '[email protected]']
['Steve', 'Stuart', '[email protected]']
['Maggie', 'Patterson', '[email protected]']
['Maggie', 'Stuart', '[email protected]']
['Jane', 'Doe', '[email protected]']
['Steve', 'Patterson', '[email protected]']
['Dave', 'Smith', '[email protected]']
['Sam', 'Wilks', '[email protected]']
['Kurt', 'Jefferson', '[email protected]']
['Sam', 'Stuart', '[email protected]']
['Jane', 'Stuart', '[email protected]']
['Dave', 'Davis', '[email protected]']
['Sam', 'Patterson', '[email protected]']
['Tom', 'Jefferson', '[email protected]']
['Jane', 'Stuart', '[email protected]']

1
['Maggie', 'Jefferson', '[email protected]']
['Mary', 'Wilks', '[email protected]']
['Neil', 'Patterson', '[email protected]']
['Corey', 'Davis', '[email protected]']
['Steve', 'Jacobs', '[email protected]']
['Jane', 'Jenkins', '[email protected]']
['John', 'Jacobs', '[email protected]']
['Neil', 'Smith', '[email protected]']
['Corey', 'Wilks', '[email protected]']
['Corey', 'Smith', '[email protected]']
['Mary', 'Patterson', '[email protected]']
['Jane', 'Stuart', '[email protected]']
['Travis', 'Arnold', '[email protected]']
['John', 'Robinson', '[email protected]']
['Travis', 'Arnold', '[email protected]']

[26]: import csv

with open('names.csv', 'r') as csv_file:


csv_reader = csv.reader(csv_file)

next(csv_reader)

for line in csv_reader:


print(line[2])

[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]

2
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]

[38]: import csv

with open('names.csv', 'r') as csv_file:


csv_reader = csv.reader(csv_file)

with open('new_names.csv', 'w') as new_file:


csv_writer = csv.writer(new_file, delimiter='-')

for line in csv_reader:


csv_writer.writerow(line)

[46]: import csv

with open('new_names.csv', 'r') as csv_file:


csv_reader = csv.reader(csv_file)
for line in csv_reader:
print(line)

['first_name-last_name-email']
['John-Doe-"[email protected]"']
['Mary-"Smith-Robinson"[email protected]']
['[email protected]']

3
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']
['[email protected]']

[50]: import csv

with open('names.csv', 'r') as csv_file:


csv_reader = csv.DictReader(csv_file)

4
for line in csv_reader:
print(line['email'])

[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]

5
[51]: import csv

with open('names.csv', 'r') as csv_file:


csv_reader = csv.DictReader(csv_file)

with open('new_names.csv', 'w') as new_file:


fieldnames = ['first_name', 'last_name']

csv_writer = csv.DictWriter(new_file, fieldnames=fieldnames,␣


,→delimiter='\t')

csv_writer.writeheader()

for line in csv_reader:


del line['email']
csv_writer.writerow(line)

[54]: import csv

with open('new_names.csv', 'r') as csv_file:


csv_reader = csv.DictReader(csv_file)

for line in csv_reader:


print(line)

OrderedDict([('first_name\tlast_name', 'John\tDoe')])
OrderedDict([('first_name\tlast_name', 'Mary\tSmith-Robinson')])
OrderedDict([('first_name\tlast_name', 'Dave\tSmith')])
OrderedDict([('first_name\tlast_name', 'Jane\tStuart')])
OrderedDict([('first_name\tlast_name', 'Tom\tWright')])
OrderedDict([('first_name\tlast_name', 'Steve\tRobinson')])
OrderedDict([('first_name\tlast_name', 'Nicole\tJacobs')])
OrderedDict([('first_name\tlast_name', 'Jane\tWright')])
OrderedDict([('first_name\tlast_name', 'Jane\tDoe')])
OrderedDict([('first_name\tlast_name', 'Kurt\tWright')])
OrderedDict([('first_name\tlast_name', 'Kurt\tRobinson')])
OrderedDict([('first_name\tlast_name', 'Jane\tJenkins')])
OrderedDict([('first_name\tlast_name', 'Neil\tRobinson')])
OrderedDict([('first_name\tlast_name', 'Tom\tPatterson')])
OrderedDict([('first_name\tlast_name', 'Sam\tJenkins')])
OrderedDict([('first_name\tlast_name', 'Steve\tStuart')])
OrderedDict([('first_name\tlast_name', 'Maggie\tPatterson')])
OrderedDict([('first_name\tlast_name', 'Maggie\tStuart')])
OrderedDict([('first_name\tlast_name', 'Jane\tDoe')])
OrderedDict([('first_name\tlast_name', 'Steve\tPatterson')])
OrderedDict([('first_name\tlast_name', 'Dave\tSmith')])
OrderedDict([('first_name\tlast_name', 'Sam\tWilks')])
OrderedDict([('first_name\tlast_name', 'Kurt\tJefferson')])

6
OrderedDict([('first_name\tlast_name', 'Sam\tStuart')])
OrderedDict([('first_name\tlast_name', 'Jane\tStuart')])
OrderedDict([('first_name\tlast_name', 'Dave\tDavis')])
OrderedDict([('first_name\tlast_name', 'Sam\tPatterson')])
OrderedDict([('first_name\tlast_name', 'Tom\tJefferson')])
OrderedDict([('first_name\tlast_name', 'Jane\tStuart')])
OrderedDict([('first_name\tlast_name', 'Maggie\tJefferson')])
OrderedDict([('first_name\tlast_name', 'Mary\tWilks')])
OrderedDict([('first_name\tlast_name', 'Neil\tPatterson')])
OrderedDict([('first_name\tlast_name', 'Corey\tDavis')])
OrderedDict([('first_name\tlast_name', 'Steve\tJacobs')])
OrderedDict([('first_name\tlast_name', 'Jane\tJenkins')])
OrderedDict([('first_name\tlast_name', 'John\tJacobs')])
OrderedDict([('first_name\tlast_name', 'Neil\tSmith')])
OrderedDict([('first_name\tlast_name', 'Corey\tWilks')])
OrderedDict([('first_name\tlast_name', 'Corey\tSmith')])
OrderedDict([('first_name\tlast_name', 'Mary\tPatterson')])
OrderedDict([('first_name\tlast_name', 'Jane\tStuart')])
OrderedDict([('first_name\tlast_name', 'Travis\tArnold')])
OrderedDict([('first_name\tlast_name', 'John\tRobinson')])
OrderedDict([('first_name\tlast_name', 'Travis\tArnold')])

7
14

July 20, 2021

[3]: import csv


html_output = ''
names = []

with open('patrons.csv', 'r') as data_file:


csv_data = csv.reader(data_file)

print(list(csv_data))

[['FirstName', 'LastName', 'Email', 'Pledge', 'Lifetime', 'Status', 'Country',


'Start'], ['1 + Reward', 'Description I will add your name to the contributors
page on\xa0my website.\n\nYou will also be eligible for Patreon-only rewards. I
will occasionally give away books that I have read, and will choose a Patron at
random to receive those.', '', '', '', '', '', ''], ['John', 'Doe',
'[email protected]', '10.00', '20.00', 'Ok', '', '2017-05-06
21:28:06.183108'], ['Dave', 'Smith', '[email protected]', '5.00',
'10.00', 'Ok', '', '2017-05-29 16:13:58.318920'], ['Mary', 'Jacobs',
'[email protected]', '5.00', '10.00', 'Ok', '', '2017-05-14
07:37:01.074648'], ['Jane', 'Stuart', '[email protected]', '5.00',
'25.00', 'Ok', '', '2016-12-30 18:12:13'], ['Tom', 'Wright',
'[email protected]', '5.00', '15.00', 'Ok', '', '2017-04-14
04:02:06.658439'], ['Steve', 'Robinson', '[email protected]', '5.00',
'20.00', 'Ok', '', '2017-03-17 02:20:14'], ['Nicole', 'Jacobs',
'[email protected]', '5.00', '20.00', 'Ok', '', '2017-03-12
17:07:29'], ['Jane', 'Wright', '[email protected]', '5.00', '25.00', '',
'', '2017-01-14 17:40:06'], ['Jane', 'Doe', '[email protected]', '2.50',
'5.00', 'Ok', '', '2017-05-14 11:20:50.798440'], ['Kurt', 'Wright',
'[email protected]', '2.00', '2.00', 'Ok', '', '2017-06-23
21:12:15.662157'], ['Kurt', 'Robinson', '[email protected]', '2.00',
'4.00', 'Ok', '', '2017-05-03 03:18:54.877885'], ['Jane', 'Jenkins',
'[email protected]', '2.00', '8.00', 'Ok', '', '2017-03-23
16:37:47.708634'], ['Neil', 'Robinson', '[email protected]', '1.50',
'3.00', 'Ok', '', '2017-05-26 19:59:51.013984'], ['Tom', 'Patterson',
'[email protected]', '1.34', '4.02', 'Ok', '', '2017-04-27
01:55:12.313799'], ['Sam', 'Jenkins', '[email protected]', '1.00',
'0.00', 'Ok', '', '2017-07-16 02:34:47.674287'], ['Steve', 'Stuart',
'[email protected]', '1.00', '1.00', 'Ok', '', '2017-06-12
03:32:00.706554'], ['Maggie', 'Patterson', '[email protected]',

1
'1.00', '2.00', 'Ok', '', '2017-05-26 01:23:14.097393'], ['Maggie', 'Stuart',
'[email protected]', '1.00', '2.00', 'Ok', '', '2017-05-19
23:11:08.624354'], ['Jane', 'Doe', '[email protected]', '1.00', '3.00',
'Ok', '', '2017-04-15 19:40:17.044921'], ['Steve', 'Patterson',
'[email protected]', '1.00', '3.00', 'Ok', '', '2017-04-09
17:14:23.591656'], ['Dave', 'Smith', '[email protected]', '1.00', '3.00',
'Ok', '', '2017-04-01 18:35:10.731005'], ['Sam', 'Wilks',
'[email protected]', '1.00', '4.00', 'Ok', '', '2017-03-01 09:40:56'],
['Kurt', 'Jefferson', '[email protected]', '1.00', '5.00', 'Ok', '',
'2017-02-24 08:23:05'], ['Sam', 'Stuart', '[email protected]', '1.00',
'5.00', 'Ok', '', '2017-02-12 00:14:31'], ['Jane', 'Stuart',
'[email protected]', '1.00', '5.00', 'Ok', '', '2017-02-06 14:52:28'],
['Dave', 'Davis', '[email protected]', '1.00', '0.00', '', '',
'2016-11-18 01:37:25'], ['Sam', 'Patterson', '[email protected]',
'1.00', '8.00', 'Ok', '', '2016-11-01 11:27:17'], ['Tom', 'Jefferson',
'[email protected]', '1.00', '10.00', 'Ok', '', '2016-09-27
09:56:48'], ['Jane', 'Stuart', '[email protected]', '1.00', '7.00', '',
'', '2016-08-09 14:42:25'], ['Maggie', 'Jefferson',
'[email protected]', '1.00', '12.00', 'Ok', '', '2016-07-26
05:02:16'], ['No Reward', 'Description: (None for No Reward)', '', '', '', '',
'', ''], ['Mary', 'Wilks', '[email protected]', '20.00', '60.00', 'Ok',
'', '2017-04-21 02:44:43.395224'], ['Neil', 'Patterson',
'[email protected]', '10.00', '80.00', 'Ok', '', '2016-11-12
17:49:37'], ['Corey', 'Davis', '[email protected]', '6.00', '90.00',
'Ok', '', '2016-04-01 15:19:52'], ['Steve', 'Jacobs',
'[email protected]', '5.00', '21.00', 'Ok', '', '2017-01-04 19:38:44'],
['Jane', 'Jenkins', '[email protected]', '5.00', '30.00', 'Ok', '',
'2017-01-15 17:24:39'], ['John', 'Jacobs', '[email protected]', '3.14',
'34.54', 'Ok', '', '2016-08-23 16:09:25'], ['Neil', 'Smith',
'[email protected]', '3.00', '24.00', 'Ok', '', '2016-11-28 02:57:48'],
['Corey', 'Wilks', '[email protected]', '2.00', '8.00', 'Ok', '',
'2017-03-26 20:13:08.207869'], ['Corey', 'Smith', '[email protected]',
'1.00', '0.00', 'Ok', '', '2017-07-05 01:50:35.171076'], ['Mary', 'Patterson',
'[email protected]', '1.00', '0.00', 'Ok', '', '2017-07-04
18:05:23.052059'], ['Jane', 'Stuart', '[email protected]', '1.00',
'2.00', 'Ok', '', '2017-05-21 19:42:36.098523'], ['Travis', 'Arnold',
'[email protected]', '1.00', '3.00', 'Ok', '', '2017-04-19
08:04:33.428559'], ['John', 'Robinson', '[email protected]', '1.00',
'4.00', 'Ok', '', '2017-03-30 14:59:33.850333'], ['Travis', 'Arnold',
'[email protected]', '1.00', '6.00', 'Ok', '', '2017-01-28 22:02:57']]

[5]: import csv


html_output = ''
names = []

with open('patrons.csv', 'r') as data_file:


csv_data = csv.reader(data_file)

2
next(csv_data)
next(csv_data)
for line in csv_data:
print(line)

['John', 'Doe', '[email protected]', '10.00', '20.00', 'Ok', '',


'2017-05-06 21:28:06.183108']
['Dave', 'Smith', '[email protected]', '5.00', '10.00', 'Ok', '',
'2017-05-29 16:13:58.318920']
['Mary', 'Jacobs', '[email protected]', '5.00', '10.00', 'Ok', '',
'2017-05-14 07:37:01.074648']
['Jane', 'Stuart', '[email protected]', '5.00', '25.00', 'Ok', '',
'2016-12-30 18:12:13']
['Tom', 'Wright', '[email protected]', '5.00', '15.00', 'Ok', '',
'2017-04-14 04:02:06.658439']
['Steve', 'Robinson', '[email protected]', '5.00', '20.00', 'Ok', '',
'2017-03-17 02:20:14']
['Nicole', 'Jacobs', '[email protected]', '5.00', '20.00', 'Ok', '',
'2017-03-12 17:07:29']
['Jane', 'Wright', '[email protected]', '5.00', '25.00', '', '',
'2017-01-14 17:40:06']
['Jane', 'Doe', '[email protected]', '2.50', '5.00', 'Ok', '', '2017-05-14
11:20:50.798440']
['Kurt', 'Wright', '[email protected]', '2.00', '2.00', 'Ok', '',
'2017-06-23 21:12:15.662157']
['Kurt', 'Robinson', '[email protected]', '2.00', '4.00', 'Ok', '',
'2017-05-03 03:18:54.877885']
['Jane', 'Jenkins', '[email protected]', '2.00', '8.00', 'Ok', '',
'2017-03-23 16:37:47.708634']
['Neil', 'Robinson', '[email protected]', '1.50', '3.00', 'Ok', '',
'2017-05-26 19:59:51.013984']
['Tom', 'Patterson', '[email protected]', '1.34', '4.02', 'Ok', '',
'2017-04-27 01:55:12.313799']
['Sam', 'Jenkins', '[email protected]', '1.00', '0.00', 'Ok', '',
'2017-07-16 02:34:47.674287']
['Steve', 'Stuart', '[email protected]', '1.00', '1.00', 'Ok', '',
'2017-06-12 03:32:00.706554']
['Maggie', 'Patterson', '[email protected]', '1.00', '2.00', 'Ok',
'', '2017-05-26 01:23:14.097393']
['Maggie', 'Stuart', '[email protected]', '1.00', '2.00', 'Ok', '',
'2017-05-19 23:11:08.624354']
['Jane', 'Doe', '[email protected]', '1.00', '3.00', 'Ok', '', '2017-04-15
19:40:17.044921']
['Steve', 'Patterson', '[email protected]', '1.00', '3.00', 'Ok',
'', '2017-04-09 17:14:23.591656']
['Dave', 'Smith', '[email protected]', '1.00', '3.00', 'Ok', '',
'2017-04-01 18:35:10.731005']

3
['Sam', 'Wilks', '[email protected]', '1.00', '4.00', 'Ok', '',
'2017-03-01 09:40:56']
['Kurt', 'Jefferson', '[email protected]', '1.00', '5.00', 'Ok', '',
'2017-02-24 08:23:05']
['Sam', 'Stuart', '[email protected]', '1.00', '5.00', 'Ok', '',
'2017-02-12 00:14:31']
['Jane', 'Stuart', '[email protected]', '1.00', '5.00', 'Ok', '',
'2017-02-06 14:52:28']
['Dave', 'Davis', '[email protected]', '1.00', '0.00', '', '',
'2016-11-18 01:37:25']
['Sam', 'Patterson', '[email protected]', '1.00', '8.00', 'Ok', '',
'2016-11-01 11:27:17']
['Tom', 'Jefferson', '[email protected]', '1.00', '10.00', 'Ok', '',
'2016-09-27 09:56:48']
['Jane', 'Stuart', '[email protected]', '1.00', '7.00', '', '',
'2016-08-09 14:42:25']
['Maggie', 'Jefferson', '[email protected]', '1.00', '12.00', 'Ok',
'', '2016-07-26 05:02:16']
['No Reward', 'Description: (None for No Reward)', '', '', '', '', '', '']
['Mary', 'Wilks', '[email protected]', '20.00', '60.00', 'Ok', '',
'2017-04-21 02:44:43.395224']
['Neil', 'Patterson', '[email protected]', '10.00', '80.00', 'Ok',
'', '2016-11-12 17:49:37']
['Corey', 'Davis', '[email protected]', '6.00', '90.00', 'Ok', '',
'2016-04-01 15:19:52']
['Steve', 'Jacobs', '[email protected]', '5.00', '21.00', 'Ok', '',
'2017-01-04 19:38:44']
['Jane', 'Jenkins', '[email protected]', '5.00', '30.00', 'Ok', '',
'2017-01-15 17:24:39']
['John', 'Jacobs', '[email protected]', '3.14', '34.54', 'Ok', '',
'2016-08-23 16:09:25']
['Neil', 'Smith', '[email protected]', '3.00', '24.00', 'Ok', '',
'2016-11-28 02:57:48']
['Corey', 'Wilks', '[email protected]', '2.00', '8.00', 'Ok', '',
'2017-03-26 20:13:08.207869']
['Corey', 'Smith', '[email protected]', '1.00', '0.00', 'Ok', '',
'2017-07-05 01:50:35.171076']
['Mary', 'Patterson', '[email protected]', '1.00', '0.00', 'Ok', '',
'2017-07-04 18:05:23.052059']
['Jane', 'Stuart', '[email protected]', '1.00', '2.00', 'Ok', '',
'2017-05-21 19:42:36.098523']
['Travis', 'Arnold', '[email protected]', '1.00', '3.00', 'Ok', '',
'2017-04-19 08:04:33.428559']
['John', 'Robinson', '[email protected]', '1.00', '4.00', 'Ok', '',
'2017-03-30 14:59:33.850333']
['Travis', 'Arnold', '[email protected]', '1.00', '6.00', 'Ok', '',
'2017-01-28 22:02:57']

4
[6]: import csv
html_output = ''
names = []

with open('patrons.csv', 'r') as data_file:


csv_data = csv.reader(data_file)

next(csv_data)
next(csv_data)
for line in csv_data:
names.append(f"{line[0]} {line[1]}")

for name in names:


print(name)

John Doe
Dave Smith
Mary Jacobs
Jane Stuart
Tom Wright
Steve Robinson
Nicole Jacobs
Jane Wright
Jane Doe
Kurt Wright
Kurt Robinson
Jane Jenkins
Neil Robinson
Tom Patterson
Sam Jenkins
Steve Stuart
Maggie Patterson
Maggie Stuart
Jane Doe
Steve Patterson
Dave Smith
Sam Wilks
Kurt Jefferson
Sam Stuart
Jane Stuart
Dave Davis
Sam Patterson
Tom Jefferson
Jane Stuart
Maggie Jefferson
No Reward Description: (None for No Reward)
Mary Wilks
Neil Patterson

5
Corey Davis
Steve Jacobs
Jane Jenkins
John Jacobs
Neil Smith
Corey Wilks
Corey Smith
Mary Patterson
Jane Stuart
Travis Arnold
John Robinson
Travis Arnold

[8]: import csv


html_output = ''
names = []

with open('patrons.csv', 'r') as data_file:


csv_data = csv.reader(data_file)

next(csv_data)
next(csv_data)
for line in csv_data:
if line[0] == 'No Reward':
break
names.append(f"{line[0]} {line[1]}")

for name in names:


print(name)

John Doe
Dave Smith
Mary Jacobs
Jane Stuart
Tom Wright
Steve Robinson
Nicole Jacobs
Jane Wright
Jane Doe
Kurt Wright
Kurt Robinson
Jane Jenkins
Neil Robinson
Tom Patterson
Sam Jenkins
Steve Stuart
Maggie Patterson
Maggie Stuart

6
Jane Doe
Steve Patterson
Dave Smith
Sam Wilks
Kurt Jefferson
Sam Stuart
Jane Stuart
Dave Davis
Sam Patterson
Tom Jefferson
Jane Stuart
Maggie Jefferson

[10]: import csv


html_output = ''
names = []

with open('patrons.csv', 'r') as data_file:


csv_data = csv.reader(data_file)

next(csv_data)
next(csv_data)
for line in csv_data:
if line[0] == 'No Reward':
break
names.append(f"{line[0]} {line[1]}")

html_output += f'<p> There are currently {len(names)} public contributors! </p>'

html_output += '\n</ul>'

for name in names:


html_output += f'\nt<li>{name}</li>'
print(html_output)

<p> There are currently 30 public contributors! </p>


</ul>
t<li>John Doe</li>
t<li>Dave Smith</li>
t<li>Mary Jacobs</li>
t<li>Jane Stuart</li>
t<li>Tom Wright</li>
t<li>Steve Robinson</li>
t<li>Nicole Jacobs</li>
t<li>Jane Wright</li>
t<li>Jane Doe</li>
t<li>Kurt Wright</li>
t<li>Kurt Robinson</li>

7
t<li>Jane Jenkins</li>
t<li>Neil Robinson</li>
t<li>Tom Patterson</li>
t<li>Sam Jenkins</li>
t<li>Steve Stuart</li>
t<li>Maggie Patterson</li>
t<li>Maggie Stuart</li>
t<li>Jane Doe</li>
t<li>Steve Patterson</li>
t<li>Dave Smith</li>
t<li>Sam Wilks</li>
t<li>Kurt Jefferson</li>
t<li>Sam Stuart</li>
t<li>Jane Stuart</li>
t<li>Dave Davis</li>
t<li>Sam Patterson</li>
t<li>Tom Jefferson</li>
t<li>Jane Stuart</li>
t<li>Maggie Jefferson</li>

[11]:
import csv

html_output = ''
names = []

with open('patrons.csv', 'r') as data_file:


csv_data = csv.DictReader(data_file)

# We don't want first line of bad data


next(csv_data)

for line in csv_data:


if line['FirstName'] == 'No Reward':
break
names.append(f"{line['FirstName']} {line['LastName']}")

html_output += f'<p>There are currently {len(names)} public contributors. Thank␣


,→You!</p>'

html_output += '\n<ul>'

for name in names:


html_output += f'\n\t<li>{name}</li>'

html_output += '\n</ul>'

8
print(html_output)

<p>There are currently 30 public contributors. Thank You!</p>


<ul>
<li>John Doe</li>
<li>Dave Smith</li>
<li>Mary Jacobs</li>
<li>Jane Stuart</li>
<li>Tom Wright</li>
<li>Steve Robinson</li>
<li>Nicole Jacobs</li>
<li>Jane Wright</li>
<li>Jane Doe</li>
<li>Kurt Wright</li>
<li>Kurt Robinson</li>
<li>Jane Jenkins</li>
<li>Neil Robinson</li>
<li>Tom Patterson</li>
<li>Sam Jenkins</li>
<li>Steve Stuart</li>
<li>Maggie Patterson</li>
<li>Maggie Stuart</li>
<li>Jane Doe</li>
<li>Steve Patterson</li>
<li>Dave Smith</li>
<li>Sam Wilks</li>
<li>Kurt Jefferson</li>
<li>Sam Stuart</li>
<li>Jane Stuart</li>
<li>Dave Davis</li>
<li>Sam Patterson</li>
<li>Tom Jefferson</li>
<li>Jane Stuart</li>
<li>Maggie Jefferson</li>
</ul>

9
15

July 20, 2021

[2]: import datetime


d = datetime.date(2021,7,20)
print(d)

2021-07-20

[3]: import datetime


tday = datetime.date.today()
print(tday.day)

21

[5]: import datetime


tday = datetime.date.today()
print(tday.weekday())
print(tday.isoweekday())

2
3

[7]: import datetime


tday = datetime.date.today()
tdelta = datetime.timedelta(days=7)
print(tday - tdelta)

2021-07-14

[8]: import datetime


tday = datetime.date.today()
tdelta = datetime.timedelta(days=7)

bday = datetime.date(2022,6,12)

till_bday = bday- tday


print(till_bday.total_seconds())

28166400.0

[13]: import datetime


dt = datetime.datetime(2021, 7 ,20, 23, 45, 40, 10000)

1
print(dt)

2021-07-20 23:45:40.010000

[14]: import datetime


dt = datetime.datetime(2021, 7 ,20, 23, 45, 40, 10000)

tdelta = datetime.timedelta(hours=12)
print(dt + tdelta)

2021-07-21 11:45:40.010000

[16]: import datetime

dt_today = datetime.datetime.today()
dt_now = datetime.datetime.now()
dt_utcnow = datetime.datetime.utcnow()

print(dt_today)
print(dt_now)
print(dt_utcnow)

2021-07-21 02:00:33.616705
2021-07-21 02:00:33.616773
2021-07-21 02:00:33.616807

[19]: import datetime


import pytz

dt_today = datetime.datetime(2021, 7, 20, 23, 45, tzinfo=pytz.UTC)


print(dt)
dt_now = datetime.datetime.now(tz=pytz.UTC)
print(dt_now)
dt_utcnow = datetime.datetime.utcnow().replace(tzinfo=pytz.UTC)
print(dt_utcnow)

2021-07-20 23:45:40.010000
2021-07-21 02:03:32.047056+00:00
2021-07-21 02:03:32.047180+00:00

[21]: import datetime


import pytz

dt_mtn = datetime.datetime.now()

mtn_tz = pytz.timezone('US/Mountain')
dt_mtn = mtn_tz.localize(dt_mtn)
dt_east = dt_mtn.astimezone(pytz.timezone('US/Eastern'))

2
print(dt_mtn.strftime('%B %d, %Y'))

dt_str = 'July 24, 2016'


dt = datetime.datetime.strptime(dt_str, '%B %d, %Y')
print(dt)

July 21, 2021


2016-07-24 00:00:00

3
16

July 20, 2021

[1]: x = 'global x'

def test():
y = 'local y'
print(x)

test()

global x

[2]: x = 'global x'

def test():
x = 'local x'
print(x)

test()
print(x)

local x
global x

[9]: import builtins

print(dir(builtins))
m = min([5,1,5,2,3])
print(m)

['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',


'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning',
'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError',
'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning',
'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',
'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning',
'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError',
'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError',
'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError',
'NameError', 'None', 'NotADirectoryError', 'NotImplemented',
'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning',

1
'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError',
'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration',
'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit',
'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError',
'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError',
'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError',
'Warning', 'ZeroDivisionError', '__IPYTHON__', '__build_class__', '__debug__',
'__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__',
'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes',
'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits',
'delattr', 'dict', 'dir', 'display', 'divmod', 'dreload', 'enumerate', 'eval',
'exec', 'execfile', 'filter', 'float', 'format', 'frozenset', 'get_ipython',
'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int',
'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map',
'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow',
'print', 'property', 'range', 'repr', 'reversed', 'round', 'runfile', 'set',
'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple',
'type', 'vars', 'zip']
1

[10]: import builtins

def my_min():
pass
m = min([5,1,5,2,3])

print(m)

[16]: def outer():


x = 'outer x'
def inner():
x = 'inner x'
print(x)

inner()
print(x)
outer()

inner x
outer x

[17]: def outer():


x = 'outer x'
def inner():
x = 'inner x'
print(x)

2
inner()
print(x)
outer()
print(x)

inner x
outer x
global x

3
17

July 20, 2021

[2]: li = [9,1,8,2,7,3,6,4,5]

s_li = sorted(li)
print('sorted variable:\t',s_li)
print('original variable:\t',li)

sorted variable: [1, 2, 3, 4, 5, 6, 7, 8, 9]


original variable: [9, 1, 8, 2, 7, 3, 6, 4, 5]

[3]: li = [9,1,8,2,7,3,6,4,5]

s_li = sorted(li)
print('sorted variable:\t',s_li)
li.sort()
print('original variable:\t',li)

sorted variable: [1, 2, 3, 4, 5, 6, 7, 8, 9]


original variable: [1, 2, 3, 4, 5, 6, 7, 8, 9]

[4]: li = [9,1,8,2,7,3,6,4,5]

s_li = sorted(li)
print('sorted variable:\t',s_li)
li.sort(reverse=True)
print('original variable:\t',li)

sorted variable: [1, 2, 3, 4, 5, 6, 7, 8, 9]


original variable: [9, 8, 7, 6, 5, 4, 3, 2, 1]

[5]: tup = [9,1,8,2,7,3,6,4,5]

s_tup = sorted(tup)
print('Tuple:\t',s_tup)

Tuple: [1, 2, 3, 4, 5, 6, 7, 8, 9]

[7]: di = {'name':'Augusto','job':'student','age':26,'os':'windows'}

s_di = sorted(di)
print('Dict\t',s_di)

1
Dict ['age', 'job', 'name', 'os']

[8]: li = [-6,-5,-4,1,2,3]

s_li = sorted(li)
print(s_li)

[-6, -5, -4, 1, 2, 3]

[9]: li = [-6,-5,-4,1,2,3]

s_li = sorted(li, key=abs)


print(s_li)

[1, 2, 3, -4, -5, -6]

[20]: class Employee():


def __init__(self,name,age,salary):
self.name = name
self.age = age
self.salary = salary

def __repr__(self):
return'{},{},${}'.format(self.name, self.age, self.salary)

e1= Employee('Carl',54,60000)
e2= Employee('Sarah',37,80000)
e3= Employee('John',42,90000)

employees = [e1,e2,e3]

def e_sort(emp):
return emp.name

s_employees= sorted(employees, key=e_sort)


print(s_employees)

[Carl,54,$60000, John,42,$90000, Sarah,37,$80000]

[22]: class Employee():


def __init__(self,name,age,salary):
self.name = name
self.age = age
self.salary = salary

def __repr__(self):
return'{},{},${}'.format(self.name, self.age, self.salary)

2
e1= Employee('Carl',32,60000)
e2= Employee('Sarah',37,80000)
e3= Employee('John',42,90000)

employees = [e1,e2,e3]

def e_sort(emp):
return emp.salary

s_employees= sorted(employees, key=e_sort, reverse=True)


print(s_employees)

[John,42,$90000, Sarah,37,$80000, Carl,32,$60000]

[19]: class Employee():


def __init__(self,name,age,salary):
self.name = name
self.age = age
self.salary = salary

def __repr__(self):
return'{},{},${}'.format(self.name, self.age, self.salary)

e1= Employee('Carl',54,60000)
e2= Employee('Sarah',37,80000)
e3= Employee('John',42,90000)

employees = [e1,e2,e3]

def e_sort(emp):
return emp.age

s_employees= sorted(employees, key=e_sort)


print(s_employees)

[Sarah,37,$80000, John,42,$90000, Carl,54,$60000]

[23]: class Employee():


def __init__(self,name,age,salary):
self.name = name
self.age = age
self.salary = salary

def __repr__(self):
return'{},{},${}'.format(self.name, self.age, self.salary)

3
e1= Employee('Carl',32,60000)
e2= Employee('Sarah',37,80000)
e3= Employee('John',42,90000)

employees = [e1,e2,e3]

def e_sort(emp):
return emp.name

s_employees= sorted(employees, key=lambda e:e.name, reverse=True)


print(s_employees)

[Sarah,37,$80000, John,42,$90000, Carl,32,$60000]

[25]: from operator import attrgetter


class Employee():
def __init__(self,name,age,salary):
self.name = name
self.age = age
self.salary = salary

def __repr__(self):
return'{},{},${}'.format(self.name, self.age, self.salary)

e1= Employee('Carl',32,60000)
e2= Employee('Sarah',37,80000)
e3= Employee('John',42,90000)

employees = [e1,e2,e3]

def e_sort(emp):
return emp.name

s_employees= sorted(employees, key=attrgetter('age'))


print(s_employees)

[Carl,32,$60000, Sarah,37,$80000, John,42,$90000]

4
18

July 20, 2021

[1]: try:
f =open('test_file.txt')
except Exception:
print('Sorry, This file does not exist')

Sorry, This file does not exist

[2]: try:
f =open('test_file.txt')
var = bad_var
except Exception:
print('Sorry, This file does not exist')

Sorry, This file does not exist

[9]: try:
f =open('test_file.txt')
var = bad_var
except FileNotFoundError:
print('Sorry, This file does not exist')
except Exception:
print('Sorry, Somenthing went wrong')

Sorry, Somenthing went wrong

[10]: try:
f =open('test_file.txt')

except FileNotFoundError as e:
print(e)
except Exception as e:
print(e)
else:
print(f.read())
f.close()

Test File Contents!

1
[11]: try:
f =open('test_file.txt')

except FileNotFoundError as e:
print(e)
except Exception as e:
print(e)
else:
print(f.read())
finally:
print("Executing Finally")

Test File Contents!


Executing Finally

[12]: try:
f =open('currupt_file.txt')

except FileNotFoundError as e:
print(e)
except Exception as e:
print(e)
else:
print(f.read())
finally:
print("Executing Finally")

Currupt File!
Executing Finally

Você também pode gostar