FileIO
JSON
To dump data to json file:
= <some_dir> / "some_file.json"
output_path = {'a': 1, 'b': 2}
params with output_path.open('w') as f:
=4) # `indent` writes each new input on a new line json.dump(params, f, indent
to load from json file:
with input_path.open() as f:
= json.load(f) result
shutil
shutil.copy(src_path, dst_path)from shutil import copyfile, rmtree, move
CSV
import csv
def read_csv_file_into_dict(filename):
with open(filename, newline='') as csvfile:
= csv.reader(csvfile, delimiter=',')
reader = {row[0]: row[1] for row in reader}
x return x
Readline
and Readlines
with open(f, "r") as f:
= f.readlines() a
Find and delete files/folders
from pathlib import Path
= list(Path('path_to_the_folder').glob('**/some_file_name'))
a for x in a:
x.unlink()
To delete a folder use shutil.rmtree
:
import shutil
"a_directory")) shutil.rmtree(Path(
Download URL file into DataFrame
One can do it directly from pandas:
import pandas as pd
# URL of the iris dataset
= 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
url
# Read the iris dataset and store it in a DataFrame
= pd.read_csv(url, header=None, names=['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'class'])
iris_df
# Display the first 5 rows of the iris DataFrame
print(iris_df.head())
or using requests to download file first:
= requests.get(url)
response
if response.status_code == 200:
with open("iris.csv", "wb") as f:
f.write(response.content)else:
print("Failed to download dataset")