Home
Cloud
Big Data
CI
Install
Samples
Java
Ubuntu
Maven
Archive
Python
|
Files
Files
Json
CSV
Files
Writing/reading to/from a file:
from pathlib import Path # import Path class path = Path('file.txt') # can be a relative or absolute path path.write_text('Hello\nPython\n' + str(3), encoding='utf-8') # create/overwrite the content of the file text = path.read_text(encoding='utf-8') print(text)
Hello Python 3
Checking if a file exists:
from pathlib import Path path = Path('file.txt') if path.exists(): print(f'the file \'{path}\' exists') else: print(f'the file \'{path}\' doesn\'t exists')
the file 'file.txt' exists
Json
Writing/reading to/from a json file:
import json # import json module from pathlib import Path x = { 'a': 1, 'b': 2 } y = { 'c': 2, 'd': 3 } z = [x, y] # ==> list of dictionaries w = { 'r': x, 's': y, 't': z } # ==> dictionary of list, set, and dictionaries path = Path('file.json') path.write_text(json.dumps(w), encoding='utf-8') text = path.read_text(encoding='utf-8') print(text)
{'r': {'a': 1, 'b': 2}, 's': {'c': 2, 'd': 3}, 't': [{'a': 1, 'b': 2}, {'c': 2, 'd': 3}]}
Indenting properly json:
import json from pathlib import Path path = Path('file.json') text_json = json.loads(path.read_text(encoding='utf-8')) path.write_text(json.dumps(text_json, indent=2), encoding='utf-8') text_indented = path.read_text(encoding='utf-8') print(text_indented)
{ "r": { "a": 1, "b": 2 }, "s": { "c": 2, "d": 3 }, "t": [ { "a": 1, "b": 2 }, { "c": 2, "d": 3 } ] }
Working with json object:
import json from pathlib import Path path = Path('file.json') path.write_text('{"a": 11, "b": [11, 12], "c": {"c1": 11, "c2":12}, "d": [{"d1": "d11", "d2": "d21"}, {"d1": "d12", "d2": "d22"}]}', encoding='utf-8') text_json = json.loads(path.read_text(encoding='utf-8')) path.write_text(json.dumps(text_json, indent=2), encoding='utf-8') print(text_json.keys()) # ==> dict_keys(['a', 'b', 'c', 'd']) print(text_json['d'][0]['d1']) # ==> d11 for item in text_json['d']: print(f'{item["d1"]}') # ==> d11, d12 b = text_json['b'] print(b) # ==> [11, 12] b0 = text_json['b'][0] print(b0) # ==> 11 c = text_json['c'] print(c) # ==> {'c1': 11, 'c2': 12} c1 = text_json['c']['c1'] print(c1) # ==> 11
CSV
import csv # import csv module from pathlib import Path path = Path('file.csv') #file.csv #name,score #a,10 #b,15 path.write_text('name,score\na,10\nb,15', encoding='utf-8') lines = path.read_text(encoding='utf-8').splitlines() reader = csv.reader(lines) # create a reader to parse lines of the csv file line = next(reader) # returns the next line in the csv file #print the line print(line) # ==> ['name', 'score'] #print the columns and their corresponding indexes in the line for index, column in enumerate(line): print(f'column_index:{index} | column_name:{column}') #print the rows for row in reader: print(f'name:{row[0]} | score:{row[1]}')
['name', 'score'] column_index:0 | column_name:name column_index:1 | column_name:score name:a | score:10 name:b | score:15
© 2010-2022
mti
tek