There is a problem with writing txt documents to MySQL database with python.

the contents of the txt document are as follows:

-
supplementary question. The code is improved as follows, but still encounter problems:

import mysql.connector
conn = mysql.connector.connect(host="localhost", port=3306, user="root", password="999", database="test", charset="utf8")
cursor = conn.cursor()
f = open("/Users/helen/Documents/dump.txt", mode = "r+")
while True:
    line = f.readline()
    if line:
        line = line.split(",")
        print(line)
        id = line[0]
        name = line[1]
        cursor.execute("insert into user2(id, name) values(%s,%s)", [id, name])
    else:
        break

f.close()
cursor.close()
conn.commit()
conn.close()

error content:

["{\\rtf1\\ansi\\ansicpg936\\cocoartf1504\\cocoasubrtf830\n"]
Traceback (most recent call last):
  File "/Users/helen/Documents/txt.py", line 16, in <module>
    name = line[1]
IndexError: list index out of range
Mar.16,2021

in the interactive interpreter of python, a statement block such as if for while is executed as a statement, while the following f.close () and while are not the same sentence block. If you write them together, the interpreter thinks that f.close () is in the while sentence block, but the indentation is not correct


grammar problems, such as indentation, Chinese characters, parentheses mismatch and other problems. Check it with pylint or simply rewrite


for i in open(yourfilename):
    id, name = i.strip().split(',')
    cursor.execute(yourcode)

or read directly with pandas
No more import with navicat


f.close () preceded by a blank line

PS: use REPL as little as possible

shit, who has gone so far, even if he doesn't answer questions? how dark is his heart when he steps on other people's questions?

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b1623a-2a846.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b1623a-2a846.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?