Perl to Python: Input/Output & Files

Input

Use raw_input() to get a string from the terminal. input() can be used to get numbers but it's better to use int(raw_input()) instead to avoid run time errors.

Output

sprintf-like formatting

"%s=%s" % (k, v)

Print keys and values of a dictionary

["%s=%s" % (k, v) for k, v in params.items()]

Print without a newline

print “hello“,

Print without spaces

print “a“ + “b“

Print with spaces

print “a“ , “b“

Files

Open a file

file = open('filename', 'w')

Read from a file

string = file.read()

Read a line

string = file.readline()

Read a file line-by-line into a list

list = file.readlines()

Write into a file

file.write(string)

Close a file

file.close()

Store any object in a file (import pickle)

pickle.dump(object, file)

Read a pickled object back from a file

object = pickle.load(file)

WorkaroundOrg: PerlToPython/InputOutput (last edited 2005-08-29 17:58:49 by ChristophHaas)