Input and Output


You know how to print to standard output with print, but by now you are probably wondering how to read from standard input or print to standard error, and how to work with filename arguments and other files.

Getting Input from the User

The simplest way to read input from the keyboard (actually, from standard input), is with the function raw_input(). For example,

 print "Please enter your name:", name = raw_input() print "Hello," + name

In this example, the comma after the first print statement prevents it from including a newline at the end of the string.

Another way to write the same thing is to include the prompt string as an argument to raw_input:

 >>> name=raw_input("Please enter your name: ") Please enter your name: Alice >>> print "Hello,"+name Hello, Alice

raw_input() does not return the newline at the end of the input.

File I/0

To open a file for reading input, you can use

 filein=open(filename, 'r')

where filename is the name of the file and r indicates that the file can be used for reading. The variable filein is a file object, which includes the methods read(), readline(), and readlines().

To get just one line of text at a time, you can use readline(), as in

 #!/usr/bin/python filein = open ("input.txt", 'r') print "The first line of input.txt is" print filein.readline() print "The second line is" print filein.readline()

which will print the first two lines of input.txt

When you run this script, the output might look something like

 The first line of input.txt is The second sentence is false. The second line is The first sentence was true.

As you can see, there is an extra newline after each line from the file. That’s because readline() includes the newline at the end of strings, and the print statement also adds a newline. To fix this, you can use the rstrip method to remove white space (including a newline) from the end of the string, like this:

 print filein.readline().rstrip() 

Alternatively, you could use a comma to prevent print from appending a newline:

 print filein.readline(),

To read all the lines from a file into a list, use readlines(). For example, you could center the lines in a file like this:

 for line in filein.readlines() :     print line.rstrip().center(80)

This script uses the center method for strings to center each line (assuming a width of 80 characters). The readlines method also includes the newline at the end of each line, so line.rstrip() is used to strip the newline from line before centering it.

To read the entire file into a single string, use read():

 for filename in filelist :     print "*** %s ***" % filename    # Display the name of the file.     filein=open(filename, 'r')       # Open the file.     print filein.read(),             # Print the contents.     filein.close()                   # Close the file.

This script will print the contents of each file in filelist to standard output. The comma at the end of the print statement will prevent print from appending an extra newline at the end of the output.

To open a file for writing output, you can use

 fileout=open(filename, 'w')

If you use ‘a’ instead of ‘w’, it will append to the file instead of overwriting the existing contents.

You can write to the file with write(), which writes a string to the file, or writelines(). This example uses the time module to add the current date and time to a log file:

 import time logfile = open (logname, 'a') logfile.write(time.asctime() + "\n")

Note that write does not automatically add a newline to the end of strings.

You can also use the method writelines(), which copies the strings in a list to the file. As with write(), you must include a newline at the end of each string if you want them to be on separate lines in the file.

To close a file when you are done using it, use the close method:

 filehandle.close()

Standard Input, Output, and Error

The sys (system) module has objects for working with standard input, output, and error. As with any module, to use sys you must import it by including the line import sys at the top of your script.

The file object sys.stdin lets you read from standard input. You can use the methods read(), readline(), and readlines() to read from sys.stdin just as you would any normal file.

 print "Type in a message. Enter Ctrl-D when you are finished." message = sys.stdin.read()

The object sys.stderr allows you to print to standard error with write() or writelines(). For example,

 sys.stderr.write("Error: testing standard error\n")

Similarly, the file object sys.stdout allows you to print to standard output. You could use sys.stdout.write as a replacement for print, as in

 sys.stdout.write("An alternate way to print\n")

Using Filename Arguments

The sys module also lets you read command-line arguments. The variable sys.argv is a list of the arguments to your script. The name of the script itself is in sys.argv[0]. For example,

 $ cat showargs.py #!/usr/bin/python import sys print "You ran %s with %d arguments:" % (sys.argv[0], len (sys.argv[1:])) print sys.argv[1:] $ ./showargs.py here are 4 arguments You ran ./showargs.py with 4 arguments: ['here', 'are', '4', 'arguments']

Note that this script uses the slice sys.argv[1:] to skip the first entry in sys.argv (the name of the script itself) when it prints the command-line arguments.

To read from filename arguments, you can use the module fileinput, which allows you to iterate through all the lines in the files in a list. By default, fileinput.input() opens each command-line argument and iterates through the lines the files contain. A typical use might look something like

 #!/usr/bin/python import fileinput for line in fileinput.input():     print "%s: %s" % (fileinput.filename(), line),

This will display the contents of each filename argument, along with the name of the file. It will interpret the argument-as a reference to standard input, and it will use standard input if no filename arguments are given. For other uses of fileinput, see http://docs.python.org/lib/module-fileinput.html.

Alternatively, you can open filename arguments just as you would any other files. For example, this script will append the contents of the first argument to the second argument:

 #!/usr/bin/python import sys filein=open (sys.argv[1], 'r') fileout=open (sys.argv[2], 'a') fileout.write(filein.read())

Using Command-Line Options

The getopt module contains the getopt function, which works rather like the shell scripting command with the same name (described in Chapter 20). You can use getopt to write scripts that take command-line options, as in

 $ ./optionScript.py -ab -c4 -d filename

To learn how to use getopt, see the Python documentation at http://docs.python.org/lib/module-getopt.html.




UNIX. The Complete Reference
UNIX: The Complete Reference, Second Edition (Complete Reference Series)
ISBN: 0072263369
EAN: 2147483647
Year: 2006
Pages: 316

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net