Python Forum
Replace String with increasing numer [SOLVED]
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Replace String with increasing numer [SOLVED]
#9
(Aug-06-2021, 10:00 PM)AlphaInc Wrote: This works fine except for one last thing - how can I save the printed output to the same file and overwrite it?

In your code you read the data from the file into a variable with <file>.read(). You can do the opposite (on a file that has been opened for writing) with <file>.write().


# read in filedata
with open('text.txt', 'r') as file :
    filedata = file.read()

# do stuff with filedata here

# write filedata out here (overwriting the file)
with open('text.txt', 'w') as file:
    file.write(filedata)
This is a bit dangerous because for a period of time, there is no data on disk. For a production script, I'd change this to write the file to another name, then after the write has succeeded, rename the file.
Reply


Messages In This Thread
RE: Replace String with increasing numer - by bowlofred - Aug-06-2021, 11:00 PM
RE: Replace String with increasing numer - by Yoriz - Aug-06-2021, 10:11 PM
RE: Replace String with increasing numer - by Yoriz - Aug-06-2021, 11:01 PM
RE: Replace String with increasing numer - by Yoriz - Aug-06-2021, 11:25 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Need to replace a string with a file (HTML file) tester_V 1 811 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  Replace string in a nested Dictianory. SpongeB0B 2 1,268 Mar-24-2023, 05:09 PM
Last Post: SpongeB0B
  Replace with upper(string) WJSwan 7 1,663 Feb-10-2023, 10:28 AM
Last Post: WJSwan
  [SOLVED] [BeautifulSoup] Why does it turn inserted string's brackets into &lt;/&gt;? Winfried 0 1,572 Sep-03-2022, 11:21 PM
Last Post: Winfried
  [SOLVED] [BeautifulSoup] Turn select() into comma-separated string? Winfried 0 1,151 Aug-19-2022, 08:07 PM
Last Post: Winfried
  Find and Replace numbers in String giddyhead 2 1,287 Jul-17-2022, 06:22 PM
Last Post: giddyhead
  Adding string after every 3rd charater [SOLVED] AlphaInc 2 1,319 Jul-11-2022, 09:22 AM
Last Post: ibreeden
Question [SOLVED] Delete specific characters from string lines EnfantNicolas 4 2,287 Oct-21-2021, 11:28 AM
Last Post: EnfantNicolas
  Replace String in multiple text-files [SOLVED] AlphaInc 5 8,267 Aug-08-2021, 04:59 PM
Last Post: Axel_Erfurt
Thumbs Up Parsing a YAML file without changing the string content..?, Flask - solved. SpongeB0B 2 2,327 Aug-05-2021, 08:02 AM
Last Post: SpongeB0B

Forum Jump:

User Panel Messages

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