IO错误22 python

IO错误22 python,python,Python,对于上面的代码,我得到以下错误。infile1包含可能文件的路径,如D:/folder/Src/em.h,但此处\n自动位于路径的末尾。我不确定为什么会发生这种情况。请帮忙 infile1 = open("D:/p/non_rte_header_path.txt","r") infile2 = open("D:/p/fnsinrte.txt","r") for line in infile1: for item in infile2: eachfile = open(l

对于上面的代码,我得到以下错误。infile1包含可能文件的路径,如D:/folder/Src/em.h,但此处\n自动位于路径的末尾。我不确定为什么会发生这种情况。请帮忙

infile1 = open("D:/p/non_rte_header_path.txt","r")
infile2 = open("D:/p/fnsinrte.txt","r")
for line in infile1:
    for item in infile2:
         eachfile = open(line,"r")

每个人都提供了评论,告诉你问题是什么,但是如果你是一个初学者,你可能不理解为什么会发生这种情况,所以我会解释

基本上,当使用python打开文件时,每一行新行(按Enter键时)都用“\n”表示

读取文件时,它会逐行读取,但除非删除“\n”,否则您的行变量将读取该文件

在图表上显示的内容\n

这对于查看一个文件是否包含多行非常有用,但您需要删除它。Edchum和alvits给出了一个很好的方法

您更正的代码为:

IOError: [Errno 22] invalid mode ('r') or filename: 'D:/folder/Src/em.h\n'

\n
应该会给你一个线索,你忘了去掉尾随的换行符。在尝试打开它之前尝试修剪
。你需要去掉新行字符,这样
行。rstip('\n')
将工作Try
eachfile=open(line.rstrip('\n'),“r”)
@EdChum谢谢。但是如果我使用rstrip选项,程序抛出错误,表示str没有attrig rstrip。请帮忙,谢谢大家。但如果我使用rstrip选项,程序会抛出错误,说str没有attrig rstrip。请帮帮我,嘿!您使用的是什么版本的python?我刚刚在我的电脑上测试了这个,它工作正常
infile1 = open("D:/p/non_rte_header_path.txt","r")
infile2 = open("D:/p/fnsinrte.txt","r")

for line in infile1:
    for item in infile2:
         eachfile = open(line.rstrip('\n'), "r")