将文本(单字母)追加到文本文件中每行的末尾 [英] Append Text (Single Letter) to the end of each line in a text file

查看:226
本文介绍了将文本(单字母)追加到文本文件中每行的末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我正在使用的文本文件的示例:

Below is an example of the text file I am working with:

437868313,2436413,Wyatt,Trenton,08/21/2003,211000010262002,211000010262002,2014,01,54435A000,510,Social Studies (Grade 5),08/14/2013,5-2,02,0,02,02,01,,,,,,100,05/29/2014,
437868313,2436413,Wyatt,Trenton,08/21/2003,211000010262002,211000010262002,2014,01,53235A000,500,Science (Grade 5),08/14/2013,5-2,02,0,02,02,01,,,,,,100,05/29/2014,
437868313,2436413,Wyatt,Trenton,08/21/2003,211000010262002,211000010262002,2014,01,58035A000,560,Physical Education (Grade 5),08/14/2013,5-2,02,0,02,02,01,,,,,,1,05/29/2014,

我正在尝试在其他每行的末尾添加字母'S'.因此,以上共有3条记录.在2014年5月29日之后,我想插入S.因此,每条记录如下:

I am trying to add simply the letter 'S' to the end of every other line. So, above, there 3 total records. Right after 05/29/2014, I want to insert the S. So a every record would look like:

437868313,2436413,Wyatt,Trenton,08/21/2003,211000010262002,211000010262002,2014,01,54435A000,510,Social Studies (Grade 5),08/14/2013,5-2,02,0,02,02,01,,,,,,100,05/29/2014,S

我意识到这很容易转换为CSV并与excel一起使用,但是在回传到txt时遇到了各种格式问题.想要用python破解它.我正在尝试使用附加,据我了解,写入将覆盖现有文件:

I realize this would be Oh so simple converting to CSV and working with excel, but I'm getting all sorts of formatting issues on the transfer back to txt. Wanted to take a crack at it with python. I'm trying to use append, from what I understand, write will overwrite my existing file:

myFile = open("myFile.txt", "a")
    for line in myFile:
        myFile.write('S')

我不经常使用python,我想知道如何索引它,以便它从第2行开始,并在逗号后追加该行的末尾,就像我上面提到的那样.

I don't use python often, I'm wondering how I can index it so it starts with line 2, and appends the very end of the line after the comma, like I noted above.

推荐答案

您需要逐行读取文件,然后再次逐行输出.这比使用CSV或什至真正使我感到恐惧的电子表格处理软件要简单得多.

You'll need to read the file line by line and then output line by line again. This is much simpler than using CSV or even spread sheet processing software which truly scares me.

with open('input.txt', 'r') as istr:
    with open('output.txt', 'w') as ostr:
        for i, line in enumerate(istr):
            # Get rid of the trailing newline (if any).
            line = line.rstrip('\n')
            if i % 2 == 0:
                line += 'S'
            print(line, file=ostr)

如果您仍在使用Python 2,请使用

If you are still using Python 2, use

ostr.write(line + '\n')

而不是print.

更新:如果要附加到行(相对于其他行),只需使用:

Update: If you want to append to every (as opposed to every other) line, simply use:

with open('input.txt', 'r') as istr:
    with open('output.txt', 'w') as ostr:
        for line in istr:
            line = line.rstrip('\n') + 'S'
            print(line, file=ostr)

这篇关于将文本(单字母)追加到文本文件中每行的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆