1. This is a file that is created and written to the new file in the console.
[Python]
#! /Usr/bin/env python
'Maketextfile. py -- create text file'
Import OS
Ls = OS. linesep
# Get filename
While True:
Fname = raw_input ('enter filename :')
If OS. path. exists (fname): www.2cto.com
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 proper line-ending
Fobj = open (fname, 'w ')
Fobj. writelines (['% s % s' % (x, ls) for x in all])
Fobj. close ()
Print 'done! '
OS. linesep indicates the end mark of the row. replacing it with the local variable name ls saves time and reduces system resource consumption.
Use raw_input () to read the file name
Use the list all [] to save each line of text (they are temporarily in memory ).
After creating the file, use writelines () to write the rows in the memory to the open file.
2. This is a small program that reads the content of a specific file.
[Python]
#! /Usr/bin/env python
'Readtextfile. py -- read and display text file'
# Get filename
Fname = raw_input ('enter filename :')
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 ()
(1) Note: because we have not removed the line terminator representing the end of each line, we have to resist the row Terminator automatically generated by the print statement-this can be achieved by adding a comma at the end of the print statement.
There is no comma after print. This is the effect: print has a comma effect:
String1 string1
String2
String2 string3
String3
(2) try-try t-else is a new statement. The limit t clause is the place where we handle errors.
Note: Before executing the two programs, you must add executable permissions to the files.
$ Chmod a + x filename