在python中将字符串作为文件打开

在python中将字符串作为文件打开,python,Python,我一直在努力从包含文件名字符串列表的文本文件中打开python中的一些文件: 例如.txt文件将包含如下名称列表 r'c:\users\computer\documents\example.txt' 我想运行一个循环,查看每一行,并查看“示例”是否在该行中。 如果是这样的话,我想打开(第行),但是我不能,并得到一个OSError:[Errno 22]无效参数: 如果我在中手动键入文件名,我可以打开它,但变量不会打开它。我尝试给行分配一个变量,替换“\n”尝试StringIO,但没有结果。我之所以

我一直在努力从包含文件名字符串列表的文本文件中打开python中的一些文件: 例如.txt文件将包含如下名称列表 r'c:\users\computer\documents\example.txt'

我想运行一个循环,查看每一行,并查看“示例”是否在该行中。 如果是这样的话,我想打开(第行),但是我不能,并得到一个OSError:[Errno 22]无效参数:

如果我在中手动键入文件名,我可以打开它,但变量不会打开它。我尝试给行分配一个变量,替换“\n”尝试StringIO,但没有结果。我之所以假设它是因为python将变量视为字符串对象,并且需要一个文件对象。但是如何将字符串行转换成同名的文件对象呢。
谢谢,
open
函数接受
str
参数,所以要实现您描述的功能,您需要执行以下操作

with open(r'names.txt') as examples:
    for line in examples:
        if 'example' in line:
            with open(line.strip()) as example_file:
                # do something with example_file
因此,每个
example\u文件将根据
names.txt
中的行逐个打开

with open('names.txt', 'r') as examples:
search = str(input('Who would you like to find?: '))
for line in examples:
    if search in line:
        print('Searching...')
        print(search, 'is here!')

我自己还在学习python,但这应该检查每一行输入的名称,如果找到或没有,打印出来。当然,你也可以根据自己的需要进行改变。让我知道这是否有帮助

发布你的代码!你把新线移走了吗<代码>打开(line.strip())
可能工作得更好。这个.txt文件是不是按字面意思保存了
r'c:\users\computer\documents\example.txt'
c:\users\computer\documents\example.txt
dates=['2016q4'、'2016q3'、'2016q2'、'2016q1']作为日期的日期:打开('c:\\users\Work computer\My documents\SUB\u FILES.txt'))as filelist2:for filelist2:if date in line:with open(line.strip())as sub_文件:for line in sub_文件:split1=line.split()if line.STARTSWITS(cik):Nl=line.split()adsh.append(Nl[1])else:pass print(adsh)dates=['2016q4'、'2016q3'、'2016q2'、'2016q1']对于日期中的日期:打开('c:\\Users\Work Computer\My Documents\SUB_FILES.txt'))as filelist2:for filelist2:if date in line:with open(line.strip())as sub_文件:for line in sub_文件:split1=line.split()if line.STARTSWITS(cik):Nl=line.split()adsh.append(Nl[1])else:pass print(adsh)试图发布代码我认为这是
line.strip()
仍然出错。.txt文件看起来像这样:r'C:\\Users\WorkComputer\Downloads\2016q4\sub.txt r'C:\\Users\WorkComputer\Downloads\2016q3\sub.txt r'C:\\Users\WorkComputer\Downloads\2016q1\sub.txt r'C:\\Users\WorkComputer\Downloads\2015q4\sub.txt这些行真的包含
r'
?为什么使用原始字符串前缀?请尝试使文件内容看起来像
C:\Users\WorkComputer\Downloads\2016q4\sub.txt
,不带引号和
r
前缀。字符串的表示方式与其实际内容之间存在很大差异。