首页 > 解决方案 > 桌面上路径的python字符串

问题描述

我正在尝试将 .csv 文件加载到我创建的数据库中。

这是我加载数据的函数,其中 path 是文件所在的路径

def load_data(path,table_name,conn):

""" 
Populate table from data in csv file at 
provided path
"""
columns = get_table_cols(table_name,conn)
coma_seperated_columns = ",".join(columns)
cursor = conn.cursor()

with open(path) as csv_file:
    reader = csv.reader(csv_file, delimiter=',')
    for row in reader:
        values = ",".join(row)
        cursor.execute(f"INSERT INTO {table_name} 
       ({coma_seperated_columns}) VALUES ({values})")'

我是这样称呼它的:

  #I have the same file at two different place because I read that the error could be coming from the 
  #fact the file is not in OneDrive
  This is line 27:   load_data(r"C:\Users\18195\Desktop\Spring 2021\CS 
         205\warmUp\State.csv","StateDatabase",conn)

  #I also tried this:
  This is line 27: load_data(r"C:\Users\18195\OneDrive\State.csv",
         "StateDatabase",conn)

我认为这是一个错误:

Traceback (most recent call last):
   File "C:/Users/18195/Desktop/Spring 2021/CS 
         205/warmUp/main.py", line 27, in <module>
      Database.load_data(r"C:\Users\18195\Desktop\Spring 2021\CS 
                           205\warmUp\State.csv","StateDatabase",conn)

当我运行调试时,我可以看到我在函数中为路径值初始化的内容不一样:

这个

"C:\Users\18195\Desktop\Spring 2021\CS 205\warmUp\State.csv"

对此 在此处输入图像描述

为什么它添加一个 \ 是导致错误的原因吗?如果不知道为什么我会收到此错误?

谢谢!

标签: pythondatabasecsvpath

解决方案


推荐阅读