user10520651
user10520651

Reputation:

Trouble with writing file

Write a function named "file_increment" that takes no parameters and doesn't return a value. This function will read the contents of a file named "orange.txt" which has only 1 line and it contains a well-formed integer. Read this integer and write its value plus 1 to a file named "sleeve.txt". If "sleeve.txt" already exists it must be overwritten.

def file_increment():
    with open("orange.txt", 'r') as rf:
        with open('sleeve.txt', 'w') as wf:
            for line in rf:
                wf.write(line+1)

I am getting error: Can't convert 'int' object to str implicitly. How do I fix this issue?

Upvotes: 2

Views: 334

Answers (3)

BernardL
BernardL

Reputation: 5464

You can open both files the with context manager which is more readable. From there compute your new line and write it to the new file in string format.

def file_increment():
    with open("orange.txt", 'r') as rf ,open('sleeve.txt', 'w') as wf:
            line = rf.read()
            new_line = int(line) + 1
            wf.write('{}'.format(new_line))

Upvotes: 0

ljnath
ljnath

Reputation: 11

You missed the type conversion, this will work for you

   def file_increment():
    with open("orange.txt", 'r') as rf:
        with open('sleeve.txt', 'w') as wf:
            for line in rf:
                wf.write('{}\n'.format(str(int(line)+1)))

Upvotes: 0

G. Anderson
G. Anderson

Reputation: 5955

If it can't do it implicitly, make it happen explicitly:

wf.write(str(int(line)+1))

Upvotes: 2

Related Questions