Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Write to file
#1
Say you have a txt. document where you want to write specific information to line 1,2,3,4 and 5 every time. Is there a way to specify this in my code?

The reason I'm asking is because my code seems to write to a different line when i run the program several times.
Reply
#2
A whole text file is merely a sequence of (unicode) characters. The computer doesn't see it as a two dimensional item as we do in a text editor. If the file is small with only a few lines as your post suggests, I would recommend reading the whole file as a list of strings and then write the whole file back on disk.
with open('spam.txt') as ifh:
    lines = list(ifh)
lines[1] = 'hello world\n'
lines[3] = 'change something\n'
with open('spam.txt', 'w') as ofh:
    ofh.writelines(lines)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  about write file wrong (Edit directly online) CNenfan 4 2,526 Jan-29-2021, 05:32 AM
Last Post: deanhystad
  write split words of sentence to file bluefrog 1 2,989 Aug-27-2018, 01:28 AM
Last Post: micseydel
  Homework - Read from/Write to file (renamed from Help help help) Amitkafle 1 3,050 Jan-11-2018, 07:24 AM
Last Post: wavic
  function to write the contents of a webpage into a new file roadrage 4 6,045 Dec-01-2016, 09:28 PM
Last Post: snippsat
  Extract data csv file and write in another file alexgrand 3 5,135 Nov-14-2016, 06:54 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020