python - 如何读取从 os.listdir 获取的文件内容?

标签 python file-not-found python-os listdir

我正在尝试读取 CSV 文件。我在两个文件夹下有两个 CSV。我收到了 CSV 文件,但当我尝试读取内容时,它说我没有这样的文件或目录。

import os
import csv

def scanCSVFile(folder, output_file_name):
    myfile = open(output_file_name, "a")
    files = os.listdir(folder)
    for file in files:
        if file.endswith('.csv'): #gives two csv files
            with open(file) as csvfile: 
                csvreader = csv.reader(csvfile)
                next(csvreader)
                for line in csvreader:
                    print (line)

    myfile.close()


def openCSV(path):
    scanCSVFile("./src/goi","goi.yml")
    scanCSVFile("./src/kanji","kanji.yml")

openCSV('.')

错误:

C:\Users\Peace\Documents\LMS>python csvToYaml.py 
Traceback (most recent call last): 
File "csvToYaml.py", line 26, in <module> openCSV('.') 
File "csvToYaml.py", line 24, in openCSV scanCSVFile("./src/goi","goi.yml") 
File "csvToYaml.py", line 14, in scanCSVFile with open(file) as csvfile:  
FileNotFoundError: [Errno 2] No such file or directory: 'Pro.csv'

最佳答案

您必须从代码中删除中断

import os,glob

folder_path = r'path'

for filename in glob.glob(os.path.join(folder_path, '*.csv')):
    with open(filename, 'r') as f:
        for line in f:
            print(line)

关于python - 如何读取从 os.listdir 获取的文件内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55825259/

相关文章:

python - 如何在Python中通过第一个字符在一个巨大的列表中有效地对元素进行分组

javascript - TS 节点:找不到源文件

python - DataGenerator在Google云端硬盘中找不到文件

c++ - 找不到 VSCode "fileName"文件

Python重启程序

python - urllib3.urlencode 字符串中的 googlescholar url

python - 使用 NCO 或 Python 测量多个 netCDF 文件的每周平均值

Python的itertools乘积内存消耗