Adding lines of text to file that may not exist

Updated TrustyTony 1 Tallied Votes 467 Views Share

Here is simple text file example for beginners, using try..except for reading old content as it may not yet exist.

def lines_to_file(fn='myfile.txt'):
    try:
        with open(fn) as my_file:
            content = my_file.read()
    except IOError:
        content = ''

    while True:
        print('''
    Content:
-------------------------------------
%s
-------------------------------------
    Want to:
        1) add a line
        2) write and quit
        3) quit and ignore changes
        ''' % content)

        response = raw_input()
        if response in list('123'):
            if response == '1':
                new_line = raw_input('Enter new line:\n')
                content += new_line + '\n'
            elif response == '2':
                with open(fn, 'w') as my_file:
                    my_file.write(content)
                break
            else:
                break
    print('Bye, bye!')

lines_to_file()
David W 131 Practically a Posting Shark

@pyTony: Can one still use raw_input in Python 3 ?

TrustyTony 888 ex-Moderator Team Colleague Featured Poster

No, but you can change that to input, which is same in Python 3. Often I however use input with new meaning and define input same as raw_input in beginning of code, so it works both in Python2 and Python3, like this:

# make code to run both in Python 2 and Python 3
try:
    input = raw_input
except:
    pass

def lines_to_file(fn='myfile.txt'):
    try:
        with open(fn) as my_file:
            content = my_file.read()
    except IOError:
        content = ''

    while True:
        print('''
    Content:
-------------------------------------
%s
-------------------------------------
    Want to:
        1) add a line
        2) write and quit
        3) quit and ignore changes
        ''' % content)

        response = input()
        if response in list('1234'):
            if response == '1':
                new_line = input('Enter new line:\n')
                content += new_line + '\n'
            elif response == '2':
                with open(fn, 'w') as my_file:
                    my_file.write(content)
                break
            else:
                break
    print('Bye, bye!')

lines_to_file()
David W 131 Practically a Posting Shark

Ok ... but then ... in Python 2.x...

num = input( msg ) # always? returns a string
                   # and your 2.x... code may have ...
                   # been expecting a number ?

                   # So ... don't you then ... have to
                   # fix-up all those inputs ... ?
TrustyTony 888 ex-Moderator Team Colleague Featured Poster

It is never recommended to use the input with evaluation. So I allways use the raw_input only. And I use overwriting of evaluating input function to ensure that code does not have dangerous input statements.

So if you want to have code running in both and use raw_input, of course you could do the opposite assignment in beginning and use raw_input in your code would be same as input for Python 3. Then however input in code would have other meaning for Python2 than for Python3.

If you have old Python2 code you want to run in Python3, you are recommended just to use the 2to3.py utility provided and finalize the code it does not manage to change by editing by hand.
How to use 2to3.py conversion, output text to scrollable window

David W 131 Practically a Posting Shark

It is never recommended to use the input with evaluation.

Are you above talking about Python 3?

I would change that to ...

It is robust coding style that always checks for valid input... perhaps, for example, using exception handling to deal with errant alpha input when numeric was expected.

So I allways use the raw_input only.

Are you saying that you never use ...
num = input( msg )
with exception handling, in Python 2.x?

And I use overwriting of evaluating input function to ensure that code does not have dangerous input statements

Perhaps you could give example(s) for the above ... so it is clear what you mean?

TrustyTony 888 ex-Moderator Team Colleague Featured Poster

Never use input in Python2, you user can do whatever he knows with it, like empty your hard disk if you are running as admin/superuser or at least delete those Holiday pictures you supposed to have backed up, if he knows how.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.