forked from mouredev/Hello-Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path06_file_handling.py
83 lines (55 loc) · 1.87 KB
/
06_file_handling.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# Clase en vídeo: https://youtu.be/TbcEqkabAWU?t=15524
### File Handling ###
import xml
import csv
import json
import os
# .txt file
# Leer, escribir y sobrescribir si ya existe
txt_file = open("Intermediate/my_file.txt", "w+")
txt_file.write(
"Mi nombre es Brais\nMi apellido es Moure\n35 años\nY mi lenguaje preferido es Python")
# print(txt_file.read())
print(txt_file.read(10))
print(txt_file.readline())
print(txt_file.readline())
for line in txt_file.readlines():
print(line)
txt_file.write("\nAunque también me gusta Kotlin")
print(txt_file.readline())
txt_file.close()
with open("Intermediate/my_file.txt", "a") as my_other_file:
my_other_file.write("\nY Swift")
# os.remove("Intermediate/my_file.txt")
# Clase en vídeo (03/11/22): https://www.twitch.tv/videos/1642512950
# .json file
json_file = open("Intermediate/my_file.json", "w+")
json_test = {
"name": "Brais",
"surname": "Moure",
"age": 35,
"languages": ["Python", "Swift", "Kotlin"],
"website": "https://moure.dev"}
json.dump(json_test, json_file, indent=2)
json_file.close()
with open("Intermediate/my_file.json") as my_other_file:
for line in my_other_file.readlines():
print(line)
json_dict = json.load(open("Intermediate/my_file.json"))
print(json_dict)
print(type(json_dict))
print(json_dict["name"])
# .csv file
csv_file = open("Intermediate/my_file.csv", "w+")
csv_writer = csv.writer(csv_file)
csv_writer.writerow(["name", "surname", "age", "language", "website"])
csv_writer.writerow(["Brais", "Moure", 35, "Python", "https://moure.dev"])
csv_writer.writerow(["Roswell", "", 2, "COBOL", ""])
csv_file.close()
with open("Intermediate/my_file.csv") as my_other_file:
for line in my_other_file.readlines():
print(line)
# .xlsx file
# import xlrd # Debe instalarse el módulo
# .xml file
# ¿Te atreves a practicar cómo trabajar con este tipo de ficheros?