Search code examples
pythonfileio

Python: How to read and change multiple numbers in a file without using .split


This is my code for trying to read in the file's numbers

def process_body(infile, outfile, modification):
'''
changing the numbers to the outfile              
'''

for line in infile.readlines():
    line = line.strip()
    num = ""
    space = " "

    if modification == "negate": 
        for char in line:
            input() #The file is really big this is here to go line by line for decoding
            if char != space:
                num += char
                
            neg = negate(num)
            print(neg)
                
            if char == space:
                pass

I am unsure what to do when char equals space, because space is unable to be negated in the negate function which is

def negate(num):
'''
absolute value of RGB value - 255
'''

num = int(num)
negate_line = num - 255
negate_line = abs(negate_line)
negate_line = str(negate_line)
return negate_line

here are a few lines from the input file

0 44 89 0 44 89 0 44 89 0 44 89 1 45 90 
1 45 90 1 45 90 1 45 90 1 45 92 1 45 92 
1 45 92 0 46 92 0 46 92 0 47 93 0 47 93 

According to the teachers instructions I am not allowed to use any string methods other than .strip. I am unable to use .split in this assignment, due to the fact it would make it really easy. Any help or trips would be greatly appreciated, I've been at this task for a few days now I can't seem to get it to quite work.


Solution

  • This code works fine on the test input you provided:

    with open('ip', 'rb') as f:
      for line in f:
        char = ""
        for c in line.strip():
          if c != " ":
            char += c
          else:
            print abs(int(char) - 255)
            char = ""
    

    You can add the if statements yourself. Also, you don't need to convert an int into a str if you just want to print it.