Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

appending a data in a specific line of a text file in Python?

Tags:

python

file

text

Let's say I have this textfile: date.txt. month|day|year

January|20|2014
February|10|
March|5|2013

I want to put 2012 after February|10|. how can i do that?

like image 561
user3483340 Avatar asked Apr 01 '14 07:04

user3483340


2 Answers

You need to read the file into memory, modify the desired line and write back the file.

temp = open('temp', 'wb')
with open('date.txt', 'r') as f:
    for line in f:
        if line.startswith('February'):
            line = line.strip() + '2012\n'
        temp.write(line)
temp.close()
shutils.move('temp', 'data.txt')

If you don't want to use a temporary file:

with open('date.txt', 'r+') as f: #r+ does the work of rw
    lines = f.readlines()
    for i, line in enumerate(lines):
        if line.startswith('February'):
            lines[i] = lines[i].strip() + '2012\n'
    f.seek(0)
    for line in lines:
        f.write(line)
like image 109
spinlok Avatar answered Nov 03 '22 01:11

spinlok


You can use the csv module, for example:

import csv

data = [
    "January|20|2014",
    "February|10|",
    "March|5|2013"
]

reader = csv.reader(data, delimiter="|")
for line in reader:
    line = [i if i != "" else "2012" for i in line]
    print(line)

Please note: csv.reader() take as argument any iterable object. So, you can easily pass it a file object

like image 32
Enrico Bianchi Avatar answered Nov 03 '22 01:11

Enrico Bianchi