Home > Software design >  Getting a single line from a txt file, turning it to string then an int and getting "ValueError
Getting a single line from a txt file, turning it to string then an int and getting "ValueError

Time:10-26

I created a program that retrieves every single line from a txt file (Numbers and text written inside) one by one, filtering it based around if it's an int or specific string. If it's an int,I use it with a function from Pyauogui(An automation library that controls keyboard and mouse) that makes it click a position on the screen (The int being used as coordinates) and if it's a string I make it do other stuff, I am sure that the code I put in the first 2 if statements does not cause any problems since I tested it with the exact code written below and it still seemed to give me the same error.

When I run the code below, It get's the first coordinate perfectly fine, clicks at the correct location. Then the second line it gives me the "ValueError: invalid literal for int() with base 10:" error.

with open('file.txt', 'r') as coords:
        # Check if the line in the coordinates.txt is a valid coordinate or a string
            # Enumarate the coordinates.txt line by line (implemented from deneme.py)
            line = str(coords.readline())
            cnt = 1
            while line:
                if "[mail]" in line:
                    #do stuff
                    print('true')
                    
                if "[sifre]" in line:
                    #do other stuff
                    print("also true")
                    
                else:
                    coordinates = str(line)
                    coordinates = coordinates.strip(',()')
                    xcoords = coordinates[0:3]
                    ycoords = coordinates[4:8]
                    xcoords = int(xcoords)
                    ycoords = int(ycoords)
                    pyautogui.click(x=xcoords,y=ycoords)
                    time.sleep(2)

file.txt looks like this:

 (294, 128)
 [mail]
 (294, 145)
 [sifre]
 (294, 200)

It get's the first line correctly, clicks at the location and then it just stops and gives me the error.

I have tried removing the [mail] and [sifre] from file.txt using the same code as before and that made it work for reason.

My purpose for writing this code was to get the first line from the text file, determine if it's a string or an int then operate based on that and go to the next line and do it again until it goes through the whole text file.

Please help.

CodePudding user response:

Here is another solution. The only difference from @NoDakker's solution is that I moved the logic outside of the loop to keep your code clean. Also this solution tries to follow pythonic idioms such as list-comps and gen-exps


def process_numbers(line: str) -> int:
  for n in line.strip(" ( )\n").split(','):
    try:
      yield int(n)
    except:
      raise StopIteration


with open('file.txt', 'r', encoding='U8') as coords:
  # Check if the line in the coordinates.txt is a valid coordinate or a string
  # Enumarate the coordinates.txt line by line (implemented from deneme.py)
  line = coords.readline()
  while line:

    if "[mail]" in line:
      #do stuff
      print('true')
    elif "[sifre]" in line:
      #do other stuff
      print("also true")
    else: 
      xcoords, ycoords = (n for n in process_numbers(line))
      print(xcoords, ycoords)
    
      pyautogui.click(x=xcoords, y=ycoords)
      time.sleep(2)
    line = coords.readline()

Happy hacking!

CodePudding user response:

I tried out your code substituting a print statement for the "pyautogui" bit, and quickly ascertained the issue you are having. Basically, you want to use an "elif" clause instead of the second "if" test. Following is a version of your program with that change.

with open('file.txt', 'r') as coords:
    # Check if the line in the coordinates.txt is a valid coordinate or a string
    # Enumarate the coordinates.txt line by line (implemented from deneme.py)
    line = str(coords.readline())
    cnt = 1
    while line:
        if "[mail]" in line:
            #do stuff
            print('true')

        elif "[sifre]" in line:     # Instead of if
            #do other stuff
            print("also true")

        else:
            coordinates = str(line)
            coordinates = coordinates.strip(',()')
            xcoords = int(coordinates[0:3])
            ycoords = int(coordinates[4:8])
            #xcoords = int(xcoords)
            #ycoords = int(ycoords)
            print("x:", xcoords, "y", ycoords)
            
        line = str(coords.readline())

Without that change, the second if/else test was being performed on the text line that contained "[mail]" and attempting to execute the "else" portion and failing. With the tweak to the code, following was the sample output at the terminal.

@Dev:~/Python_Programs/Parse$ python3 Parse.py 
x: 294 y 128
true
x: 294 y 145
also true
x: 294 y 200

Give that a try and see if it meets the spirit of your project.

  • Related