Writing to a specific line in at .txt file

Question:
I’m trying to write to a specific line in a .txt file, everything I try won’t work, I know
\n will create a new line but that’s not what I want, I want to write to a specific line e.g line 6 without the other lines, here’s what I currently have

Repl link:

Qfile = str(random.randint(100000, 999999)) + ".txt"
f = open(Qfile, "x")
f.writelines("test")[6]
1 Like

Are you wanting to have 5 “blank line” first, then something on line 6? Or are you only wanting to “overwrite” what’s already on line 6?

I would like to be able to write certain things on certain lines and also overwrite things on certain lines, so for example there may be contents in a .txt file like this

item1
item2
item3
item4
item5

is there a way to overwrite item2 or item 4 in a .txt file

You’ll probably want to use readlines() to read each line of the file into a list. You can then change the value of that item in the list. After changing, you can the write the entire list back to the file.

ok, would I be correct in saying that there isn’t a way to overwrite a certain line like in the code I listed?

Not that I’m aware of, but I could be wrong. I’m not overly experience in reading and writing text file with Python. I usually stick to the basics. I’m sure other more experienced Python developers will chime in if there’s an easier way.

ok thank you, i’ll keep this open in case someone does know a way of doing that!

def write_line(file_name:str, line:int, content:str):
  line -= 1 # Python starts counting at 0, but people start counting at one. This accounts for that.
  with open(file_name, "r") as file: # Open the file in read mode
    lines = file.readlines() # Assign the file as a list to a variable
    lines[line] = content + "\n" # Replace the proper line with the provided content
  with open(file_name, "w") as file: # Open the file in write mode
    file.write("".join(lines)) # Write the modified content to the file

write_line("myFile.txt", 2, "Never gonna give you up.") # Execute function

I tested this and it works.

3 Likes

^^^^

This is basically what I was talking about. Reading the contents into a list, then updating the value of a specific item (“line”) in the list and the writing the contents back to the text file.

1 Like

Nice function. I may have to “borrow” this one. :grinning:

3 Likes

@kerbalcats0 Sorry, but your code makes it looks like you have 999999 txt files, because you’re opening one seemingly at random, with the starting range at 1 million. Do you have 1 million files?

1 Like
def write_line(file_path: str, line_number: int, text: str, chunk_size: int = 1024):
  with open(file_path, 'r') as file:
      lines = [
          text if (i + 1 == line_number) else line.rstrip('\n')
          for chunk in iter(lambda: file.read(chunk_size), '')
          for i, line in enumerate(chunk.split('\n'))
      ]

  with open(file_path, 'w') as file:
      file.write('\n'.join(lines))

  print("Success")

write_line('test.txt', 5, 'ok.')

@anon40284853 has already posted a working version, but this one also works. Also, it uses chunks to read and write, making it faster, especially when reading and modifying lines in larger files.

1 Like
write_line("myFile.txt", 2, "Never gonna give you up.") # Execute function
  File "/home/runner/TanMuffledMaintenance/main.py", line 5, in write_line
    lines[line] = content + "\n" # Replace the proper line with the provided content
IndexError: list assignment index out of range
1 Like

it creates a file with a name of a random number

1 Like

Try mine:

def write_line(file_path: str, line_number: int, text: str, chunk_size: int = 1024):
  with open(file_path, 'r') as file:
      lines = [
          text if (i + 1 == line_number) else line.rstrip('\n')
          for chunk in iter(lambda: file.read(chunk_size), '')
          for i, line in enumerate(chunk.split('\n'))
      ]

  with open(file_path, 'w') as file:
      file.write('\n'.join(lines))

  print("Success")

write_line('test.txt', 5, 'ok.')
1 Like

How many lines are in that file? If there’s only one line then of course it will give that error. This is to replace an existing line, not create a new one. Evidently line 2 of the specified file did not exist.

1 Like

thank you this works!

2 Likes

I see now, could you alter it so that if the line I’m trying to write to doesn’t exist, it will create lines to that point, if you can’t don’t worry if you can’t, thank you for your help!

2 Likes

I think modifying

Like so:

def write_line(file_name:str, line:int, content:str):
  line -= 1 # Python starts counting at 0, but people start counting at one. This accounts for that.
  with open(file_name, "r") as file: # Open the file in read mode
    lines = file.readlines() # Assign the file as a list to a variable
    while len(lines) < line:
        lines.append("")
    lines[line] = content + "\n" # Replace the proper line with the provided content
  with open(file_name, "w") as file: # Open the file in write mode
    file.write("".join(lines)) # Write the modified content to the file

write_line("myFile.txt", 2, "Never gonna give you up.") # Execute function

Should work.

3 Likes

Here, if the line doesn’t exist, it will create the necessary lines and then write the desired text:

def write_line(file_path: str, line_number: int, text: str, chunk_size: int = 1024):
    lines_to_add = max(0, line_number - sum(1 for _ in open(file_path)))
    with open(file_path, 'a') as file:
        file.writelines('\n' for _ in range(lines_to_add))

    with open(file_path, 'r') as file:
        lines = [
            text if (i + 1 == line_number) else line.rstrip('\n')
            for chunk in iter(lambda: file.read(chunk_size), '')
            for i, line in enumerate(chunk.split('\n'))
        ]

    with open(file_path, 'w') as file:
        file.write('\n'.join(lines))

    print("Success")

write_line('test.txt', 5, 'ok.')
2 Likes