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?
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)
                        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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With