【问题标题】:Can I use with statements inside of for loops?我可以在 for 循环中使用 with 语句吗?
【发布时间】:2020-03-26 00:15:17
【问题描述】:

我正在尝试创建一个“文件爬虫”来遍历我的目录并在文件中搜索关键字以返回目录。我有 .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')

【问题讨论】:

  • 您能否提供您的程序正在使用的所有文件?
  • 如果你打印class_notes,我想你会发现列表中的一些值是一个空字符串。

标签: python file-io with-statement


【解决方案1】:

这一行引用的文件

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]

它将保留字符串,修剪空字符串,无值和类似的

【讨论】:

  • 每当我写入文件时,它都会在文件末尾自动附加一个“,”。有没有办法解决这个问题。如果需要,我可以附加导致问题的函数。
猜你喜欢
  • 2018-03-11
  • 1970-01-01
  • 1970-01-01
  • 2011-02-24
  • 2019-06-17
  • 1970-01-01
  • 2021-11-08
  • 2011-01-14
  • 2022-01-21
相关资源
最近更新 更多