Python文件读取+写入 [英] Python File Read + Write
问题描述
我正在将数据库从一个定制的MSSQL CMS移植到MYSQL - Wordpress。我正在使用Python读取一个txt文件,其中包含 \ t
划定的列和每行一行。我试图编写一个Python脚本来读取这个文件(fread),并最终创建一个带有insert语句的MYSSQL准备.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 =打开('d:/icm_db/users.txt','r')
用于fread中的行:
print line;
fread.close()
fwrite.close()
我如何内爆每一行,这样我可以访问每一列,并做生意?
我需要生成每行多个MYSQL插入语句我读。所以...对于每行读取,我会产生如下:
$ b $ pre $ INSERT INTO`wp_users`(`ID`, `user_login`,`user_name`)
VALUES(line [0],'line [2]','line [3]');
尽管这很容易实现, csv 模块。
>>> import csv
>>> reader = csv.reader(open('C:/www/stackoverflow.txt'),delimiter ='\t')
>>>对于阅读器中的行:
...打印行
...
['1','John Smith','Developer','http://twiiter.com/johns' ,'Chicago,IL']
['2','John Doe','Developer','http://whatever.com','Tallahassee,FL']
$ c $另外,正如所指出的那样,Python中不需要分号。试着去踢这个习惯:)
I am working on porting over a database from a custom MSSQL CMS to MYSQL - Wordpress. I am using Python to read a txt file with \t
delineated columns and one row per line.
I am trying to write a Python script that will read this file (fread) and [eventually] create a MYSSQL ready .sql file with insert statements.
A line in the file I'm reading looks something like:
1 John Smith Developer http://twiiter.com/johns Chicago, IL
My Python script so far:
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()
How can I "implode" each line so I can access each column and do business on it?
I need to generate multiple MYSQL insert statements per line I read. So... for each line read, I'd generate something like:
INSERT INTO `wp_users` (`ID`, `user_login`, `user_name`)
VALUES (line[0], 'line[2]', 'line[3]');
解决方案 Although this is easily doable, it does become easier with the csv module.
>>> 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']
Also, as pointed out, semicolons are not needed in Python. Try to kick that habit :)
这篇关于Python文件读取+写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!