In [1]:
# input function reads from standard in and returns a string
answer = input("enter your name:")
print(answer)
In [2]:
# files can be opened using the open function, which creates a file object
f = open( 'new_file.txt', 'w' ) # attention overwrites existing file
# important functions: read, write, readlines, writelines
# dir(f)
f.write("Hallo Welt!")
f.close()
In [3]:
# writelines
lines = []
for i in range(12):
lines.append("Number: " + str(i) + '\n')
print(lines)
f = open( 'new_file.txt', 'a' ) # open file and append to it
f.writelines(lines)
f.close()
In [4]:
# usage of with to open files is recommended in python
with open('new_file.txt', 'r') as f: # open file for reading
content = f.read() # get the whole content of a file into a string
print(content)
In [5]:
with open('new_file.txt', 'r') as f: # open file for reading
lines = f.readlines()
print(lines)
f.close()
In [6]:
with open('data.txt', 'r') as f:
lines = f.readlines()
#print(lines)
data = {}
# iterate over all lines in the file
for line in lines:
if line.startswith('#'): # skip comments
continue
left, right = line.split(':') # split splits a string at the occurence of the keyword
data[ left.strip() ] = float(right) # strip removes leading and tailing spaces
print(data)
In [7]:
# the pickle class is used to serialize python variables (convert them to bytestrings)
import pickle
In [8]:
d = { 1: 'green', 2: 'blue', 3: 'red' }
pickle.dumps(d)
Out[8]:
In [9]:
with open('save.p', 'wb') as f:
pickle.dump(d, f)
In [10]:
with open('save.p', 'wb') as f:
pickle.dump(d, f)
In [11]:
with open('save.p', 'rb') as f:
loaded_data = pickle.load(f)
print(loaded_data)
In [12]:
# create a folder for the data files
import os
# get current working directory
work_path = os.getcwd()
print(work_path)
In [13]:
# define path for data files
data_path = os.path.join(work_path, 'data/')
# check if folder exists already
if not os.path.exists(data_path):
os.mkdir(data_path)
In [14]:
with open('real_estate.csv', 'r') as f:
f.readlines()
In [15]:
import pandas as pd
df = pd.read_csv( 'real_estate.csv' )
print(df)
#print(df.values.tolist())
JSON (/ˈdʒeɪsən/ JAY-sən),[1] or JavaScript Object Notation, is an open standard format that uses human-readable text to transmit data objects consisting of attribute–value pairs. It is used primarily to transmit data between a server and web application, as an alternative to XML.
Although originally derived from the JavaScript scripting language, JSON is a language-independent data format. Code for parsing and generating JSON data is readily available in many programming languages.
In [16]:
cat employees.json
In [17]:
import json
d = json.load( open('employees.json') )
d['employees'][1]
Out[17]:
In [ ]: