2

I have a script that opens a csv file, applies a substitution and then writes out to a new file then deletes the old one.

with open('file-presub.csv', 'r') as reader, open('file-postsub.csv','w') as writer: for row in reader: row = re.sub('(\+*,[^,]*,[^,]*,[^,]*,\ 0)', ' (Core)\\g<1>', row) writer.write(row) os.remove("file-presub.csv") 

Is there any way I can make it so I just edit the file-presub.csv and write it out with the same filename instead of making a second file and deleting the original? I'd like to avoid importing OS just for this one line.

Of course if it's not possible I'm able to import OS, just asking if it's possible at all.

3
  • 1
    You can open file both in read and write modes: stackoverflow.com/questions/6648493/… Commented Nov 1, 2017 at 11:34
  • 1
    instead of opening first file in read mode you can open it in write mode and perform write operations without having another file. Commented Nov 1, 2017 at 11:35
  • Look at the fileinput module. Commented Nov 1, 2017 at 11:35

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.