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

jessie555

我试图创建一个“文件搜寻器”以遍历我的目录,并在文件中搜索关键字以返回目录。我有.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')
爱德华多·法奇内利

该行引用的文件

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]

它将保留字符串,修剪空字符串,无值等

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

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

我可以在一个循环中使用2个循环语句吗?

可以在for循环中使用多个if语句吗?

我可以在vuejs循环中使用slot吗?

我可以在C ++中的for循环中使用指针吗?

我可以不在循环中使用调度组吗?

我可以在for循环中使用bash括号扩展吗?

我可以在 foreach 循环中使用 eloquent 模型吗

可以在for循环中使用lambda吗?

在我的循环中使用UPDATE吗?

我可以在一个循环中使用多个 for 循环吗?

在for循环中使用if语句

我可以在循环中使用itertools :: PutBack :: put_back吗?

我们可以在PHP的foreach循环中使用IterateAggregate或Iterator吗?

我可以在一个 while 循环中使用 2 个计数器吗?

我可以在Python的for循环中使用变量作为索引吗?

我可以在 for 循环中使用指针的位置/地址作为终止条件吗?

我可以在一个foreach循环中使用两组变量吗?

可以在if循环中放入if语句吗?

可以在循环中使用相同的变量名吗?

可以在 *ngFor 循环中使用函数吗?

我可以在printf语句中使用条件语句吗?

任何人都可以帮助我在 php 的 foreach 循环中使用 json 数据吗?

在 MATLAB 的 for 循环中使用 if 语句

避免在for循环中使用if语句?

Lua if 语句在 for 循环中使用函数

我可以在for循环中添加条件吗?

我可以在 PHP 中使用 DECLARE 作为 SQL 语句吗

我可以在case语句中使用数组吗?