If you are trying to insert data in bulk to Mysql the best would be to use LOAD DATA instead of doing it in a loop on top of an interpreted language, which is inevitably slower. However there is less flexibility if you need to transform data but that shouldn't be a problem in your case. All you're doing is get rid of carriage return. This is a plain delimited file without heavy transformation.
The mydb.commit()
is misplaced. It should be called after running an insert/update. On the first iteration there is nothing to be committed.
But this is not efficient. I suggest that you take full advantage of transactions. Start a transaction at the beginning, do your loop and commit at the end. In case of error, you roll back. The added benefit is data integrity. If an error occurs, the data already inserted is "undone" so you don't end up with garbage due to a partial import of data.
Schema:
try:
conn.autocommit = False
# insert loop..
# Commit your changes
conn.commit()
except mysql.connector.Error as error:
print("Failed to update record to database rollback: {}".format(error))
# reverting changes because of exception
conn.rollback()
See for example: Use Commit and Rollback to Manage MySQL Transactions in Python
This alone should improve performance but you have to test it to measure the gain.
Not performance-related, but you can also use a context manager whenever possible, for instance when opening/writing to a file. So:
agefile = open("C:/Users/juczi/Desktop/New Folder/" + plik, "r")
becomes:
with open("C:/Users/juczi/Desktop/New Folder/" + plik, "r") as agefile:
# do something
and you don't have to bother closing the file, this is done automatically.