我想从excel中读取内容,并将内容写入文本文件。下面的源代码完成了我的工作,除了一件事。我从excel中读取并写入文本文件的示例文本文件的内容如下所示:
test1\ntest2\ntest3\ntest4\ntest5然而,我希望它是这样的:
test1
test2
test3
test4
test5我试着用wb模式写文件,但它不能工作。
这是我的代码。我该怎么办?
from __future__ import print_function
from os.path import join, dirname, abspath
import xlrd
def omer():
#excel file is opened.
xl_workbook = xlrd.open_workbook('codes_autoscript_table_export.xls')
#sheet names of the excel file is returned.
sheet_names = xl_workbook.sheet_names()
#print (sheet_names)
#print (sheet_names[0])
#first sheet of the excel can be chosen in two ways :
# xl_sheet = xl_workbook.sheet_by_name(sheet_names[0]) #first way
xl_sheet = xl_workbook.sheet_by_index(0) # second way
#print (xl_sheet.name)
#any row of the chosen sheet can be read.
#print (xl_sheet.row(0)) # returns [text:'AUTOSCRIPT', text:'SOURCE', text:' ']
#print (xl_sheet.row(1)) # returns [text:'VFOWNER', text:'(CLOB) mbo.setValueNull("OWNERGROUP")', text:' ']
row = xl_sheet.row(1)
filename = str(row[0])[6:-1] + ".py"
filecontent = str(row[1])[13:-1]
print (filename)
print (filecontent)
print ("# of columns : " + str(xl_sheet.ncols)) # Number of columns
print ("# of rows : " + str(xl_sheet.nrows)) # Number of columns
for i in range(1, xl_sheet.nrows): # Iterate through rows
oneRow = xl_sheet.row(i)
filename = str(oneRow[0])[6:-1] + ".txt"
filecontent = str(oneRow[1])[13:-1]
#print (filename)
my_file = open('./output/' + filename ,'w')
my_file.write(filecontent)
my_file.close()
if __name__ == '__main__':
omer()发布于 2016-02-17 22:28:24
在将更改writeline写入后追加新行
my_file.write(filecontent + '\n')如果内容已经是字符串,则使用writelines回写所有行
content = 'test1\ntest2\ntest3\ntest4\ntest5' #generates a list removing the new line
with open('myfile.txt', 'w') as f:
f.writelines(content)如果这个不起作用,试试这个
content = content.split() # returns ['test1', 'test2'....]
with open('myfile.txt', 'w') as f:
for i in content:
f.write(i + '\n')https://stackoverflow.com/questions/35459221
复制相似问题