1

I am attempting to collect only certain type of data from one file. After that the data is to be saved to another file. The function for writing for some reason is not saving to the file. The code is below:

def reading(data): file = open("model.txt", 'r') while (True): line = file.readline().rstrip("\n") if (len(line) == 0): break elif (line.isdigit()): print("Number '" + line + "' is present. Adding") file.close() return None def writing(data): file = open("results.txt", 'w') while(True): line = somelines if line == "0": file.close() break else: file.write(line + '\n') return None file = "model.txt" data = file somelines = reading(data) writing(data) 

I trying several things, the one above produced a TypeError (unsupported operand). Changing to str(somelines) did solve the error, but still nothing was written. I am rather confused about this. Is it the wrong definition of the "line" in the writing function? Or something else?

1
  • reading returns None, which you store in somelines but don't use anyway. Other than that it doesn't actually do anything. How are you expecting to get the data out of the reading function? Commented Jun 18, 2021 at 13:19

2 Answers 2

2

See this line in your writing function:

 file.write(line + '\n') 

where you have

 line = somelines 

and outside the function you have

somelines = reading(data) 

You made your reading function return None. You cannot concat None with any string, hence the error.

Sign up to request clarification or add additional context in comments.

Comments

1

Assuming you want one reading function which scans the input file for digits, and one writing file which writes these digits to a file until the digit read is 0, this may help:

def reading(file_name): with open(file_name, 'r') as file: while True: line = file.readline().rstrip("\n") if len(line) == 0: break elif line.isdigit(): print("Number '" + line + "' is present. Adding") yield line def writing(results_file, input_file): file = open(results_file, 'w') digits = reading(input_file) for digit in digits: if digit == "0": file.close() return else: file.write(digit + '\n') file.close() writing("results.txt", "model.txt") 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.