python - 如果它不在最后一行,Python 无法打开写在文本文档上的文件路径
问题描述
帮助
所以,我仍然是 python 的初学者,我决定制作一个简单的程序,当你告诉它你家里有什么食材时,它会告诉你一些食谱要做。
我决定根据一个文本文件来制作它,这意味着我将有一个文本文件,上面有整理好的成分,如果输入的成分与文件中的成分匹配,它将读取它们下面的行,它将包含另一个文本文件的路径,该文件将包含供人们阅读的完整配方。
如果文件路径的行下没有行,则代码有效。这很奇怪,因为当我将其更改为打印,而不是打开文件路径时,它会正确打印出来,但是当我尝试让 python 打开它时,它会显示以下错误消息:
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'
请帮忙,它一直说那里有一个 \n 而没有!
这是代码,以防你们需要一些上下文
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
解决方案
我会插入一个新行的支票
lenPath = len(file)
if file[(lenPath-1):lenPath == '\n':
file[:(lenPath-1)]
g = open(file.readline())
推荐阅读
- angular - Angular/HTML 中的 NgIf 和 NgElse
- javascript - 如何安全地公开显示 Firestore 子集合的 UID
- python - 如何为 scipy.signal.find_peaks 指定阈值
- django - 如何在 Django 中制作可重用的页面片段?
- optaplanner - 在 OptaPlanner 的约束中使用 HardMediumSoftScore 时出现异常
- javascript - 如何在html标签中显示链接
- install4j - install4j v9.0后如何检测windows代理设置
- react-native - React Native-Styling Tab Navigator
- python - 如何在 Django ORM 中触发 bulk_create 之后的动作?
- node.js - 如何在 npm 中运行单个测试?