简体   繁体   中英

IOError: [Errno 2] No such file or directory trying to open a file in python

I am new to Python so please forgive the following basic code and problem, but I have been trying to figure out what is causing the error I am getting.

Here is what I am trying to do:

  1. loop through a specific folder
  2. iterate each csv files in that specific folder
  3. perform calculations

Here is my code:

import os
    import csv

    def get_all_files(directory):
        dir_list = os.listdir(directory)
        csv_files = []
        for e in dir_list:
            if e.endswith('.csv'):
               csv_files.append(e)
         return csv_files

    def sum_from_csv(csv_file):
        cr = csv.reader(open(csv_file, 'r'))
        cr.next()
        file_content=cr.readlines()

        #initialize throughput total as zero
        throughput_total=0
        #array to save throughput in every iteration
        throughput_dataset=[]

        for line in file_content:
          line=line.strip()
          data=line.split(",")[1]
          float_data=float(data)
          throughput_total+=float_data
          throughput_dataset.append(float_data)
        #to calculate number of dataset
        dataset_length=len(throughput_dataset)
        throughput_average=throughput_total/dataset_length
        throughput.append(throughput_average)
        print "Throughput-total is",throughput_total
        print "Average is",throughput_average

   csv_files = get_all_files('/home/gwthamy/Desktop/MyProject/siddhi-benchmarks/filter-4.0.0-M20/filtered-results-filter-4.0.0-M20')

   for each in csv_files:
        sum_from_csv(each)

Here is the error I am getting:

IOError: [Errno 2] No such file or directory: 'output-0-1502441456439.csv'

I have confirmed that the folder and file do exist. What is causing the IOError and how to I resolve it? Also, is there anything else wrong with my code that would prevent me from performing the entire task?

Thanks in advance

this should work !

import os

dir = '/home/gwthamy/Desktop/MyProject/siddhi-benchmarks/filter-4.0.0-M20/filtered-results-filter-4.0.0-M20'
for each in get_all_files(dir):
    sum_from_csv(os.path.join(dir, each))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM