首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从excel写入文本文件时,换行符不能正常工作

从excel写入文本文件时,换行符不能正常工作
EN

Stack Overflow用户
提问于 2016-02-17 22:19:36
回答 1查看 1.5K关注 0票数 0

我想从excel中读取内容,并将内容写入文本文件。下面的源代码完成了我的工作,除了一件事。我从excel中读取并写入文本文件的示例文本文件的内容如下所示:

代码语言:javascript
复制
test1\ntest2\ntest3\ntest4\ntest5

然而,我希望它是这样的:

代码语言:javascript
复制
test1
test2
test3
test4
test5

我试着用wb模式写文件,但它不能工作。

这是我的代码。我该怎么办?

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

发布于 2016-02-17 22:28:24

在将更改writeline写入后追加新行

代码语言:javascript
复制
my_file.write(filecontent + '\n')

如果内容已经是字符串,则使用writelines回写所有行

代码语言:javascript
复制
content = 'test1\ntest2\ntest3\ntest4\ntest5' #generates a list removing the new line

with open('myfile.txt', 'w') as f:
    f.writelines(content)

如果这个不起作用,试试这个

代码语言:javascript
复制
content = content.split() # returns ['test1', 'test2'....]
with open('myfile.txt', 'w') as f:
    for i in content:
        f.write(i + '\n')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35459221

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档