In [2]:
# raw input function reads from standard in and returns a string
answer = raw_input("enter your name:")
print answer
# input function takes python code as input !attention!
answer = input("python input:")
print answer
In [4]:
# files can be opened using the open function, which creates a file object
f = open( 'new_file.txt', 'w' ) # attention overwrites existing file
# importan functions: read, write, readlines, writelines
#dir(f)
f.write("Hallo Welt!")
f.close()
In [5]:
# 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 [6]:
# 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 [7]:
with open('new_file.txt', 'r') as f: # open file for reading
lines = f.readlines()
print lines
f.close()
In [8]:
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 [9]:
# the pickle class is used to serialize python variables (convert them to bytestrings)
# cPickle is written in C and a lot faster as normal pickle, but cannot be subclassed
import cPickle as pickle
In [10]:
d = { 1: 'green', 2: 'blue', 3: 'red' }
pickle.dumps( d )
Out[10]:
In [11]:
with open('save.p', 'w') as f:
pickle.dump(d, f)
In [12]:
with open('save.p', 'r') as f:
loaded_data = pickle.load(f)
print loaded_data
In [13]:
# create a folder for the data files
import os
# get current working directory
work_path = os.getcwd()
print work_path
In [14]:
# 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 [17]:
with open('real_estate.csv', 'r') as f:
f.readlines()
In [18]:
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 [34]:
cat employees.json
In [41]:
import json
d = json.load( open('employees.json') )
d['employees'][1]
Out[41]: