The following problems involve the makeTextFile. py and readTextFile. py scripts.
[Note] the source code of makeTextFile. py and readTextFile. py found on the network is slightly different from the original book example.
'Maketextfile. py -- create text file'
Import OS
# Get filename
While True:
Fname = raw_input ('enter file name :')
If OS. path. exists (fname ):
Print "*** ERROR: '% s' already exists" % fname
Else:
Break
# Get file content (text) lines
All = []
Print "\ nEnter lines ('.' by itself to quit). \ n"
# Loop until user terminates input
While True:
Entry = raw_input ('> ')
If entry = '.':
Break
Else:
All. append (entry)
# Write lines to file with NEWLINE line terminator
Fobj = open (fname, 'w ')
Fobj. write ('\ n'. join (all ))
Fobj. close ()
Print 'done! '
'Readtextfile. py -- read and display text file'
# Get filename
Fname = raw_input ('enter file name :')
Print
# Attempt to open file for reading
Try:
Fobj = open (fname, 'R ')
Handle t IOError, e:
Print "*** file open error:", e
Else:
# Display contents to the screen
For eachLine in fobj:
Print eachLine,
Fobj. close ()
3-8.
Python code. Copy the script to your file system and modify it. You can add comments, modify the prompt ('>' is too monotonous), and modify the code to make them look more comfortable.
[Answer]
.
3-9.
Port. If Python is installed on different types of computer systems, check whether the OS. linesep value is different. Write down the operating system type and linesep value.
[Answer]
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C: \ Documents ents and Settings \ root> python
Python 2.7 (r27: 82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> Import OS
>>> OS. linesep
'\ R \ N'
>>>
In a linux operating system
[GCC 4.1.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> Import OS
>>> OS. linesep
'\ N'