Apr-20-2019, 01:50 AM
I suspect that it might be file corruption. There may be leading or trailing invisible characters, or even invisible characters inside your integer literals which python isn't recognizing as whitespace. The ascii code for
"\n"
is 10. The ascii codes for 0-9 are 48 through 58 inclusive. If you run the following script on your file, it will detect anything that isn't in this character set:import re # Open the file you want to scan for invalid characters. numero = int(input('informe o pedido\n:')) # We use regular expression matching to detect the bad characters. validChar = re.compile(r"\A\d|\n\Z") with open(f'Pedidos_test\{numero}.txt', 'r') as f: for lineNum, lineVal in enumerate(f.readlines()): for charNum, currentChar in enumerate(lineVal): if not validChar.search(currentChar): print("Invalid character detected on line {}, at char {}".format(lineNum + 1, charNum + 1)) print("Invalid character code: {}".format(ord(currentChar)))If I'm right, and you have a bad file, the unwanted characters will be invisible, so we just print out their code points to see what they are. To remove them, we just run the script below:
# Open the file you want to scan for invalid characters. numero = int(input('informe o pedido\n:')) # We use regular expression matching to detect the bad characters. validChar = re.compile(r"\A\d|\n\Z") cleanStr = "" with open(f'Pedidos_test\{numero}.txt', 'r') as f: for char in f.read(): if validChar.search(char): cleanStr += char with open(f'Pedidos_test\{numero}.txt', 'w') as f: f.write(cleanStr)