2

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?

1
  • Welcome to SO btw! Since you're new here, please don't forget to mark the answer accepted which helped most in solving the problem. Commented Oct 25, 2018 at 22:02

3 Answers 3

2

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

wf.write(str(int(line)+1)) 
Sign up to request clarification or add additional context in comments.

2 Comments

I am still getting write() argument must be str, not int.
Sorry, see my edit. You have to make it an int to do math, then back to a str to write it
0

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))) 

Comments

0

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)) 

Comments