以下是我正在使用的文本文件的示例:
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.所以每条记录都会像:
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来解决它。我试图使用追加,据我所知,写将覆盖我现有的文件:
myFile = open("myFile.txt", "a")
for line in myFile:
myFile.write('S')
我经常不使用python,我想知道如何将其编入索引,因此它从第2行开始,并在逗号之后追加该行的最后一行,就像我上面提到的那样。
答案 0 :(得分:8)
您需要逐行读取文件,然后再次逐行输出。这比使用CSV甚至是真正让我害怕的电子表格处理软件更简单。
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,请使用
ostr.write(line + '\n')
而不是print
。
更新:如果您要追加每个(而不是其他所有)行,只需使用:
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)
答案 1 :(得分:3)
打开文件进行读取和写入,并枚举输入文件。 Idenfity使用mod 2的偶数行。将s追加到偶数行并写入输出文件。
with open('myfile.txt', 'rb') as infile, with open('outfile.txt', 'wb') as outfile:
for lineno, line in enumerate(infile):
if lineno % 2 == 0:
line = line + 'S'
outfile.write(line)
OP根据他的编辑想要每条记录,因此无需测试偶数行。
import os
with open('myfile.txt', 'rb') as infile, with open('outfile.txt', 'wb') as outfile:
for line in infile:
line = line.replace(os.linesep, 'S' + os.linesep)
outfile.write(line)
答案 2 :(得分:0)
最简单的方法是将文件作为一个块打开,并用逗号和换行符替换逗号和换行符。
open("data.txt").read().replace(',\n','S,\n').write()
答案 3 :(得分:0)
试试这个:
filename = "file.txt"
file = open(filename, "r")
for line in file:
print line.replace("\n","S\n")
答案 4 :(得分:0)
试试这个:
myFile = open("myFile.txt", "a")
Colist = str(myFile.read()).split('\n')
for line in Colist:
myFile.write(line + 'S' + '\n')