简体   繁体   English

Python写入行流

[英]Python write to line flow

Part of my script is taking values and putting them to a text file delimited by tabs. 我的脚本的一部分是获取值并将其放入由制表符分隔的文本文件中。 So I have this: 所以我有这个:

for linesplit in fileList:
    for i in range (0, len(linesplit)):
        t.write (linesplit[i]+'\t')

I get as an output in the file what I expect in the first line but in the following lines they all start with a \\t in them, like is: 我在文件中得到的输出与第一行的预期相同,但是在接下来的几行中,它们都以\\ t开头,如下所示:

value1    value2    value3
    value1    value2    value3
    value1    value2    value3

Also, why don't I need to add a t.write('\\n') after the second FOR loop to create the newlines? 另外,为什么我不需要在第二个FOR循环之后添加t.write('\\ n')来创建换行符? I would expect the code above to produce one long line of tab separated values but it doesn't. 我希望上面的代码能产生一长行的制表符分隔值,但事实并非如此。 If I include the t.write('\\n') then the tabs issue is resolved but I get double '\\n'... 如果我包含t.write('\\ n'),则选项卡问题已解决,但我得到了双'\\ n'...

it doesn't produce what you want because original lines ( linesplit ) contain end of line character ( \\n ) that you're not stripping. 它不会产生您想要的内容,因为原始行( linesplit )包含您没有剥离的行尾字符( \\n )。 insert the following before your second for loop: 在第二个for循环之前插入以下内容:

linesplit = linesplit.strip('\n')

That should do the job. 那应该做的。

I'm sorry... After I hit submit it dawned on me. 对不起...我点击提交后,它突然降临了。 My last value already has a \\n in it which causes the newline. 我的最后一个值中已经有一个\\ n,导致换行。

您的最后一个值必须有一个导致两个问题的“ \\ n”:第一个问题是因为它在换行符后输出'\\ t',第二个问题应该很明显-神秘的换行符来自您的最后一个值。

you linesplit variable could have newlines. 您的lineplit变量可能包含换行符。 just use strip() to remove it. 只需使用strip()删除它即可。

您的"value3"字符串实际上是"value3\\n" ,它解释了神奇的换行符以及除第一行以外的所有选项卡。

The inner loop isn't required. 不需要内部循环。 Perhaps you meant to use: 也许您打算使用:

t.write('\t'.join(linesplit))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM