fall_05 2024-12-25 15:45 采纳率: 76.9%
浏览 10
已结题

csv文件在python中读取存在问题


import csv
import networkx as nx

# 创建图
G_undirected = nx.Graph()  # 无向图,用于1号线和2号线
G_directed = nx.DiGraph()   # 有向图,用于3号线

# 读取CSV文件并构建图
def load_data(filename):
    with open(filename, 'r', encoding='utf-8') as file:
        reader = csv.DictReader(file)  # 使用DictReader方便通过列名访问数据
        for row in reader:
            line = row['line']
            start_station = row['start_station']
            end_station = row['end_station']
            distance = int(row['distance'])
            time = int(row['time'])
            direction = row['direction']
            
            # 根据线路类型添加边到相应的图
            if line == "3号线":
                G_directed.add_edge(start_station, end_station, distance=distance, time=time, direction=direction)
            else:
                G_undirected.add_edge(start_station, end_station, distance=distance, time=time)

# 打印图的信息以确认数据加载正确
def print_graph_info():
    print("Undirected Graph (Lines 1 and 2):")
    print("Nodes:", G_undirected.nodes())
    print("Edges:", G_undirected.edges(data=True))
    
    print("\nDirected Graph (Line 3):")
    print("Nodes:", G_directed.nodes())
    print("Edges:", G_directed.edges(data=True))

# 主函数
def main():
    load_data('subway')  # 确保CSV文件名和路径正确
    print_graph_info()

if __name__ == "__main__":
    main()

为什么我的csv文件提示说找不到啊,它就叫subway啊,放在桌面不知道为什么无法找到它

  • 写回答

2条回答 默认 最新

  • 九月镇灵将 2024-12-25 15:52
    关注

    你确定subway文件跟你程序在同一目录吗?要直接文件名的话需要在同一目录
    而且,按道理不应该是subway.csv吗

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 1月2日
  • 已采纳回答 12月25日
  • 创建了问题 12月25日