6

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?

2 Answers 2

13

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Doens't work, shutils.move()
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.