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
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.
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.
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
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.
@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?
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.')
@CoderElijah 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.
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
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.')
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.
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!
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
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.')