[Tutor] Append mode dilemma

biboy mendz bibsmendez at gmail.com
Wed Dec 9 19:11:54 CET 2009


Hello all!
I'm trying to use the append mode when opening and writing to a file
but i cant get it to work my way. When run in the present code,
the user inputs are expectedly 'appended' but not in a newline below the 
last
line of the existing file. Instead it starts from where the last line end. I
want the append to start on a newline of its own. Can you please let me
know what am I missing? I dont quite get it what my book reference states:

"Any file opened with 'a' will be opened for append. All writes to files 
opened
with 'a' will be from end-of-file, even if you seek elsewhere during 
access. If
the file does not exist it will be created, making it the same as if you 
opened
the file in 'w' mode."



#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
Chapter 3.1 :
Core Python Programming 2nd Edition by Wesley Chun
Filename: appendFile.py
Created: 09-Dec-2009
v1.0: append user input to existing file
'''

import os, sys

def main():
while True:
fname = raw_input('Enter filename to APPEND your input lines: ')
if os.path.isdir(fname):
print('%s is a directory!') % fname
elif not os.path.exists(fname):
print 'this is APPEND mode; select CREATE to create new file'
elif fname.isspace():
print 'Space is not allowed'
else:
#os.path.exists(fname):
#found candidate for edit
break

all = [] # container list to hold user input lines
print("file '%s' will be appended by your input\n") % fname
quit_prompt = "[start your input to quit enter 1 dot]--> "

while True:
entry = raw_input(quit_prompt)
if entry == '.':
break
else:
all.append(entry)

confirm = raw_input('save file to disk?(y/N)')
confirm = confirm.lower() #convert to lowercase
if confirm == 'y':
fobj = open(fname, 'a')
fobj.write('\n'.join(all))
fobj.close()
print('DONE! open %s to view your file') % fname
else:
print 'not saving to disk!'

if __name__ == '__main__':
main()

-- 
Regards,
bibs M.

Host/Kernel/OS  "cc000002695" running Linux 2.6.31-5.slh.4-sidux-686 
[sidux 2009-02 Αιθήρ - kde-full - (200907141427) ]
www.sidux.com



More information about the Tutor mailing list