Concise Python Tutorials

Source: Internet
Author: User
Tags readline

In many cases, you will want your program to interact with the user (possibly yourself). You will get input from the user and then print some results. We can use the Raw_input and print statements separately to accomplish these functions. For output, you can also use a variety of str (string) classes. For example, you can use the Rjust method to get a string that is right-aligned by a certain width. Use Help (str) for more details.

Another commonly used input/output type is the processing of files. The ability to create, read, and write files is necessary for many programs, and we will explore how to implement them in this chapter.

File

You can open a file by creating an object of the file class, using the read, ReadLine, or write methods of the file class to properly read and write files. The ability to read and write files depends on the pattern you specify when you open the file. Finally, when you are done with the file, you call the Close method to tell Python that we have finished using the file.

Working with files

Example 12.1 using Files

#!/usr/bin/python
# Filename: using_file.py
poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''
f = file('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file
f = file('poem.txt')
# if no mode is specified, 'r'ead mode is assumed by default
while True:
line = f.readline()
if len(line) == 0: # Zero length indicates EOF
break
print line,
# Notice comma to avoid automatic newline added by Python
f.close() # close the file

(source file: code/using_file.py)

Output

$ python using_file.py
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.