PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, August 29, 2022

[FIXED] How to read/loop through multiple .csv files in a folder using Google Colab python, then assign each file as a function parameter

 August 29, 2022     csv, google-colaboratory, google-drive-shared-drive, pandas, python     No comments   

Issue

I'm currently using Google Colab and already mounted my Google Drive. I have a folder inside the drive that has multiple .csv files

e.g. folder name: dataset

folder content: data1.csv, data2.csv, data3.csv, and so on

I want to iterate through every file in the folder, then make the file a function parameter

Here's my code but still didn't work

from google.colab import drive
drive.mount('/content/drive/')

def myfunction(data):
###function detail here###

dir = '/content/drive/dataset'

for files in dir:
  myfunction(pd.read_csv('filename'))

Thank you


Solution

You have to iterate over files using a function like os.listdir. Here's an example that uses this function and defensively checks that what is read is a csv file. I've used Google Colab's sample_data folder so that the code is reproducible; you will need to change the dir variable to point to your Google Drive folder.

import pandas as pd
import os

def myfunction(data):
  print(data)

dir = 'sample_data'

for file in os.listdir(dir):
  if file.endswith(".csv"):
    myfunction(file)


Answered By - Andrew Chisholm
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing