sqlite 正在将目录中的所有文件从xlsx转换为sql [已关闭]

5tmbdcev  于 2023-01-09  发布在  SQLite
关注(0)|答案(1)|浏览(167)

这个问题是由打字错误或无法再重现的问题引起的。虽然类似的问题在这里可能是on-topic,但这个问题的解决方式不太可能帮助未来的读者。
44分钟前就关门了。
Improve this question
我100%确定路径是正确的。我打印了所有文件的路径,第一个是C:/Users/bean/Desktop/EU\aal_l.xlsx我必须隐藏或显示扩展名吗?这有关系吗?我不明白为什么它不能检测文件。

import os
import pandas as pd
import sqlite3

# Iterate over the files in the directory

for filename in os.listdir("C:/Users/bean/Desktop/EU"):
    # Check that the file is a XLSX file
    if filename.endswith(".xlsx"):
    # Read the data from the file into a dataframe
    df = pd.read_excel(filename)

    # Connect to the database
    conn = sqlite3.connect("mydatabase.db")
    
    # Create a table for the data
    df.to_sql(filename, conn, if_exists="replace")
    
    # Commit the changes
    conn.commit()
    
    # Close the connection
    conn.close()

错误没有这样的文件或目录:'aal_l.xlsx'

igsr9ssn

igsr9ssn1#

我看到你的评论,你已经使它的工作,但有两个主要的改进我想提出。
1.在处理路径时使用pathlib,从一开始就可以解决您的问题,并且只对XLSX文件使用glob,而不是迭代所有内容并跳过。
1.只打开和关闭一次与DB的连接,打开和关闭for循环的每个迭代都是浪费。

import sqlite3
from pathlib import Path

import pandas as pd

path_to_excels = Path("C:/Users/bean/Desktop/EU")

conn = sqlite3.connect("mydatabase.db")

for filename in path_to_excels.glob("*.xlsx"):
    df = pd.read_excel(filename)
    df.to_sql(str(filename), conn, if_exists="replace")
    conn.commit()

conn.close()

相关问题