我可以在for循环中使用with语句吗?

2024-04-23 07:17:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个“文件爬虫”来遍历我的目录,并在文件中搜索关键字以返回目录。我有一个.txt文件,它包含了我用with语句访问的笔记的所有标题,我用for循环顺序搜索这些内容。我的问题是产生了一个错误

下面是classes.txt的一个示例,它们是目录的名称

Physics,GEology,

下面是notes.txt的示例,它们是.txt的名称

ROck,other rock,

这是你在文件里能找到的

This is a rock and it is formed by silicon

如果我输入'silicon'作为键,它会产生错误

这是功能,我知道它有点马虎,所以请容忍我

def find_notes():

    print('enter key words you had in your notes')
    key = input('KEY> ')
    with open('classes.txt','r') as f:
        exist = False
        contents = f.read()
        contents = contents.split(',')
        for i in contents:
            os.chdir(i)
            with open('notes.txt', 'r') as notes: # save notes into a .txt in the working direcotry,,, Check
                class_notes = notes.read()
                class_notes = class_notes.split(',')
            for r in class_notes:
                notes_file = r + '.txt'
                print(notes_file)
                with open(notes_file, 'r') as stinkey:
                    real = stinkey.read()
                    if key in real:
                        file = os.getcwd()
                        file = file.split('\\')
                        exist = True
                        file_name = r + '.txt'
            reverse_dir()
        if exist == True:
            print('The notes are in:', file[-1] )# print the directory
            print('The title of the notes are ', file_name)
        else:
            print('Notes could not be found')

Tags: 文件keyin目录txtforaswith
1条回答
网友
1楼 · 发布于 2024-04-23 07:17:57

此行引用的文件

with open('notes.txt', 'r') as notes:

没有内容(空字符串),或者文本在行中有两个逗号。当这种情况发生时,这一行:

class_notes = class_notes.split(',')

将分配一个空字符串“”,该字符串将链接到.txt并导致程序尝试打开一个名为“.txt”的不存在的文件

编辑:将分割线替换为:

class_notes = [x for x in class_notes.split(',') if x]

它将保留字符串、删减空字符串、无值和类似值

相关问题 更多 >