Python:在第一个函数中使用 oswalk 查找文件,传递名称,然后尝试在第二个函数中打开

Python: Using oswalk in first function to find files, pass name, then trying to open in second function

我正在尝试使用两个函数来查找文件并处理它们,其输出最终将发送到 SQlite3 数据库。当不是函数时,我有第二部分工作,但为此,需要输入要处理的每个文件的名称。我希望它自动化,因此是 oswalk 的第一个功能。但是,当我添加第一个找到文件并将 returns 它们添加到第二个函数的函数时,出现了问题。在发布的代码中,我只是想测试文件是否正在传递并且可以一次打开和读取一个文件。

关于正在发生的事情的注释和指向输出的指针(将粘贴在代码下方)在下面的代码中散列。

import os
import fnmatch

def findFiles (path, filter):
    Files = []
    for root, dirs, files in os.walk(path):
        for file in fnmatch.filter(files, filter):
           Files.append(os.path.join(root, file))
    return Files

def fastq2SQlite(Files):
    for file in Files:
        print file    ## At this point, I have a list of files.  See "A" below.  

        with open(file, 'r'):  ##If this block is then added, it's evident that the files shown 
                               ##in "A" are not being recognized as files.  Output is "A" 
                               ##transposed, each line a letter of a file name.
            for line in file:
                print line

输出"A"
C:/Users/Documents/JKC10/test.txt
C:/Users/Documents/JKC10/test2.txt
C:/Users/Documents/JKC10/test3.txt

我什至试图通过修改文件使文件名变为(示例)来读取文件,但均未成功: 'C:/Users/Documents/JKC10/test_out.txt'

通过添加如下所示的块:

def fastq2SQlite(Files):
    for file in Files:
        f = "'" + file + "'"
import os
import fnmatch

def findFiles (path, filter):
    Files = []
    for root, dirs, files in os.walk(path):
        for file in fnmatch.filter(files, filter):
           Files.append(os.path.join(root, file))
    return Files

def fastq2SQlite(Files):
    for file_ in Files:
        print file_    

        with open(file_, 'r') as dummy_file:

            for line in dummy_file:
                print line

你也应该避免使用file等关键字作为变量名,它会覆盖原始对象并可能导致一些严重的问题,这是一个很好的编程习惯。