csv Python格式无效

sd2nnvve  于 11个月前  发布在  Python
关注(0)|答案(1)|浏览(115)

在Windows上运行Python 3.12。尝试导入多个.csv文件并导出为多个颜色图。我想添加测量单位和标记,但我似乎无法获得try:部分的格式。我能想到的对第11-13行的每一个更改给予我SyntaxError。

import pandas as pd
import matplotlib.pyplot as plt

file_paths = ["1.csv, "2.csv","3.csv", "4.csv"]
import os

try:
    open (r"C:/Users/USER/FOLDER/CSV_FILES")
except: os.path.isfile(path)
with open(path, "r") as f:
    pass
finally IOError
    print("The file cannot be opened")

file_paths = [os.path.join(directory, filename) for filename in 
os.listdir(directory) if filename.endswith(".csv")]

colors = plt.cm.viridis(range(len(file_paths)))

for i, file_path in enumerate(file_paths):
    df = pd.read_csv(file_path)

    # Define data to plot
    x = df["column1"]
    y = df["column2"]

    # Create plot with unique color
    plt.plot(x, y, color=colors[i], label=file_path.split("/")[-1].split(".")[0]) 
         
    plt.legend()
    plt.title("Graph from", file_path)

    # Save plot as image
    plt.savefig(f"graph_{i + 1}.png")
    plt.clf()

字符串
我尝试了一些更简单的'导入操作系统'部分,我得到了权限错误PermissionError:[Errno 13]权限拒绝:'C:/Users/USER/FOLDER/CSV_FILES'

directory = open(r"C:/Users/USER/FOLDER/CSV_FILES")
 assert os.path.isfile(path)
 with open(path, "r") as f:
     pass
 file_paths = [os.path.join(directory, filename) for filename in os.listdir(directory) if filename.endswith(".csv")]


应为4.csv文件提供具有多种颜色的图形

mnemlml8

mnemlml81#

你没有在列表的第一个元素(1.csv)之后关闭双引号,在第3行:

file_paths = ["1.csv, "2.csv","3.csv", "4.csv"]

字符串
请注意,这个元素在语法高亮显示时看起来也不一样。那一行应该是:

file_paths = ["1.csv", "2.csv","3.csv", "4.csv"]

相关问题