Python文件读写

6 投票
5 回答
42095 浏览
提问于 2025-04-15 11:55

我正在把一个自定义的MSSQL内容管理系统的数据库迁移到MYSQL - Wordpress上。我使用Python来读取一个用\t分隔列的文本文件,每一行代表一条记录。

我想写一个Python脚本来读取这个文件(fread),并最终生成一个可以用来在MYSQL中插入数据的.sql文件,里面包含插入语句。

我正在读取的文件中的一行看起来像这样:

1    John Smith    Developer  http://twiiter.com/johns   Chicago, IL

到目前为止,我的Python脚本是:

import sys

fwrite = open('d:/icm_db/wp_sql/wp.users.sql','w')

fread = open('d:/icm_db/users.txt','r')

for line in fread:
    print line;


fread.close()
fwrite.close()

我该如何“合并”每一行,以便我可以访问每一列并对其进行处理呢?

我需要为我读取的每一行生成多个MYSQL插入语句。所以...对于每一行,我会生成类似这样的内容:

INSERT INTO `wp_users` (`ID`, `user_login`, `user_name`) 
VALUES (line[0], 'line[2]', 'line[3]');

5 个回答

0

你可能想要的是这样的代码:data=line.split("\t")
这会给你一个很方便的序列对象来使用。
(顺便说一下,Python里不需要用分号。这里有一个:print line;

正如Dave提到的,这样做可能会留下一个换行符。在分割之前,先用strip()去掉行首和行尾的空白,比如这样:line.strip().split("\t")

1

知道确切的列数可以帮助你更好地记录自己的代码:

fwrite = open("d:/icm_db/wp_sql/wp.users.sql","w")

for line in open("d:/icm_db/users.txt"):
  name, title, login, location = line.strip().split("\t")

  # Double up on those single quotes to avoid nasty SQL!
  safe_name = name.replace("'","''")
  safe_login = name.replace("'","''")

  # ID field is primary key and will auto-increment
  fwrite.write( "INSERT INTO `wp_users` (`user_login`, `user_name`) " )
  fwrite.write( "VALUES ('%s','%s');\n" % (safe_name,safe_login) )
10

虽然这件事很简单,但使用csv模块会让它变得更容易。

>>> import csv
>>> reader = csv.reader(open('C:/www/stackoverflow.txt'), delimiter='\t')
>>> for row in reader:
...     print row
...
['1', 'John Smith', 'Developer', 'http://twiiter.com/johns', 'Chicago, IL']
['2', 'John Doe', 'Developer', 'http://whatever.com', 'Tallahassee, FL']

另外,正如提到的,Python里不需要用分号。尽量改掉这个习惯哦 :)

撰写回答