簡體   English   中英

錯誤消息“ TypeError:預期的str,字節或os.PathLike對象,而不是列表”,而代碼與工作版本的代碼基本相同

[英]Error message “TypeError: expected str, bytes or os.PathLike object, not list”, while code is basically same code as a working version

我是編程新手,幾天前才剛開始使用python3.x。 另外,在遇到問題時,我從來沒有主動使用過該網站,盡管它已經為我節省了很多時間,所以如果我的問題格式不是最好的,請原諒我。

我的目標是通讀x .csv文件並將所需的數據繪制到圖形中。 該程序的第一個版本已經在運行:

import glob
import csv
import matplotlib.pyplot as plt
from datetime import datetime


files = glob.glob('C:\\Users\Serdar\Desktop\SEMINARARBEIT\Twitch\Twitch\Summary\*.csv')
a = "Fortnite"

listViewers = []
listTimestamp=[]


for x in range(4519):
    csv_file = csv.reader(open(files[x], "r"), delimiter=",")

    for row in csv_file:
        if a == row[1]:
            datetime_object = datetime.strptime(row[4], '%Y-%m-%d %H:%M:%S')
            listTimestamp.append(datetime_object)
            listViewers.append(float(row[2]))


t = listTimestamp
s = listViewers
plt.plot(t, s, 'r')

plt.gcf().autofmt_xdate() 
plt.xlabel('Time')
plt.ylabel('Viewers')
plt.title('Fortnite: Viewers over Time')
plt.grid(True)
plt.show()

在這里,我正在掃描4500個文件並繪制圖形。 沒問題 在第二個程序中,我只想獲取一個.csv文件(這是一個文件,其數據結構不同於4500以前的文件),並以相同的方式對其進行處理。

這是我得到標題錯誤的地方。 這是代碼:

import glob
import csv
import matplotlib.pyplot as plt


file = glob.glob('C:\\Users\Serdar\Desktop\SEMINARARBEIT\Twitch\Twitch\Stream\1529010392.472129.csv')
a = "Fortnite"

listViewers = []
listStreamers=[]

csv_file2 = csv.reader(open(file, "r"), delimiter=",")
for row in csv_file2:
    if a == row[1]:

        listStreamers.append(row[23])
        listViewers.append(float(row[10]))


t = listStreamers
s = listViewers
plt.plot(t, s, 'r')

plt.gcf().autofmt_xdate() 
plt.xlabel('Streamers')
plt.ylabel('Viewers')
plt.title('Fortnite: Viewers over Time')
plt.grid(True)
plt.show()

我知道我正在做類似將列表類型對象保存在“ csv_file2”中的操作,但是它需要字符串或字節等。但是我不知道第一個代碼的區別在哪里。 鑒於我的經驗不足,這可能是一件微不足道的事情,但我懷疑是在第二個代碼的文件中,某些地方我有“ []”作為值。 難道這被視為清單? 另一個理論可能是第二批文件中包含“ ˆÐ”之類的字符,這可能也是一個問題嗎?

不過我真的不確定,希望您能幫助我

您遇到的問題是因為glob.glob總是返回文件列表 ,您的代碼在第一個版本的代碼中可以正確處理,但在第二個版本中則不能正確處理。 由於您指定了特定文件,因此glob.glob返回包含一個對象的列表。 只需更改代碼以將文件變量視為列表即可,它應該可以正常工作:

csv_file2 = csv.reader(open(file[0], "r"), delimiter=",")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM