Google Colab读取CSV代码触发TypeError错误,请求技术解决方案
Hey there! Let's break down what's going wrong here and fix it quickly.
Why You're Getting the Error
First, let's clarify what files.upload() returns: it's a dictionary where the keys are the uploaded filenames, and the values are the raw binary content of those files.
Your custom ls() function is trying to pass this entire dictionary to io.StringIO(), which expects a string or None as its initial value—hence the TypeError: initial_value must be str or None, not dict. On top of that, you're trying to iterate over io.StringIO like it's a list of file objects, which doesn't make sense here.
Correct Ways to Handle the Uploaded Files
You don't need a custom ls() function to get the uploaded filenames, and reading the CSV is straightforward once you handle the binary content properly. Here are two common approaches:
Option 1: Get Uploaded Filenames (Simple Version)
If you just want a list of the uploaded filenames, you can directly grab the keys from the uploaded dictionary:
from google.colab import files uploaded = files.upload() # Get list of uploaded filenames divisas = list(uploaded.keys()) print("Uploaded files:", divisas)
Option 2: Read the CSV File (Using Pandas)
Most people use Pandas to work with CSVs in Colab. You'll need to decode the binary content to a string first, then pass it to pd.read_csv():
from google.colab import files import pandas as pd import io uploaded = files.upload() # Pick the first uploaded file (or specify the filename directly) filename = next(iter(uploaded.keys())) divisas_df = pd.read_csv(io.StringIO(uploaded[filename].decode('utf-8'))) # Check the data print(divisas_df.head())
Option 3: Read the CSV File (Using Built-in csv Module)
If you prefer not to use Pandas, you can use Python's built-in csv module:
from google.colab import files import csv import io uploaded = files.upload() filename = next(iter(uploaded.keys())) # Decode binary content to string and split into lines csv_content = io.StringIO(uploaded[filename].decode('utf-8')) # Read the CSV reader = csv.reader(csv_content) for row in reader: print(row)
Key Takeaways
uploadedis always a dictionary, not a list of files or a string.- To access the file content, use
uploaded[filename]and decode it from binary to string if needed. - You don't need to reinvent a "list files" function—just use
list(uploaded.keys())!
内容的提问来源于stack exchange,提问作者Pedro Puertas

