0

Help

So, I'm still a starter on python and I decided to make a simple program that, when you tell it the ingredients you have in your home, it tells you some recipes to make.

I decided to make it based on a text file, which means I will have a text file with the ingredients sorted out on it, and if the ingredients the person typed in match the ones on the file, it will read the line under them, which will contain a path for another text file which will have the full recipe for the person to read.

The code works IF there is no line under the line with the path to the file. Which is weird, because when I changed it to print, not open the file path, it printed it out correctly, but when I try to make python open it, it displays this error message:

Traceback (most recent call last):

File "C:/Users/nailu/PycharmProjects/Recipe find yes/find rcipe.py", line 66, in <module>

g = open(file.readline())

OSError: [Errno 22] Invalid argument: 'C://Users//nailu//Desktop//Projeto receita//Receitas//receita bolo de maca.txt\n'

please help, it keeps saying theres a \n in there when there isnt!

Here is the code in case you guys need some context

word=input("Digite aqui:")


count = 1
count2 = 1



s=" "
while (s):
    s = file.readline()
    L = s.split()
    if palavro in L:
        print("I found a recipe for you!")
        time.sleep(1)
        see=input("Would you like to see it?  y/n")
        if see=="y":
            g = "a"
            g = open(file.readline())
            h=" "
            while (h):
                h = g.readline()
                print(h)
                count2= (count2+ 1)
                time.sleep(1)
        else:
            print("Ok, going over to the next recipe...")
        time.sleep(0.5
  • But there is a \n, it's shown in the error. A "\n" means new-line, just use a string method to remove it, eg. myPathString.replace("\\n", "") – Petronella Jul 01 '20 at 12:37

2 Answers2

-1

I would insert a check for a new line

lenPath = len(file)
if file[(lenPath-1):lenPath == '\n':
  file[:(lenPath-1)]
g = open(file.readline())
freqnseverity
  • 146
  • 1
  • 7
-1
  1. instead of making a variable s that acts as a value for "True", you could just say

    while True: do stuff

  2. turn "palvaro" into a string. but removing the quotation marks, you're implying that there is a variable named 'palvaro', which is not the case.

  3. you need to define file, or if this is a snippet of your code, it would help to see what the file.txt looks like to get more context.

  4. the open() function takes only a file path / file object.