overwrite some data in a python file - python

I was hoping someone could help me, I am currently trying to add some data into a text file, however the way I am doing it isnt giving me what I want. I Have a file with 20+ lines in it with text and want to overwrite the first 30 characters of the file with 30 new characters. The code I have deletes all the content and adds the 30 characters only. Please help :)
file=open("text.txt", "w")
is there something wrong with this to why its reoving all of the original data too instead of simply overwriting over it?

One way is to read the whole file into a single string, create a new string with first 30 characters replaced and rewrite the whole file. This can be done like this:
with open("text.txt", "r") as f:
data = f.read()
new_thirty_characters = '<put your data here>'
new_data = new_thirty_characters + data[30:]
with open("text.txt", "w") as f:
f.write(new_data)
Ideally, you have to check that file contains more than 30 characters after it's read. Also, do not use file and other reserved names as variable names.

Related

Python: Inserting content of entire textdocument after a certain string in 2nd document

Im pretty new to Python, but I've been trying to get into some programming in my free time. Currently, im dealing with the following problem:
I have 2 documents, 1 and 2. Both have text in them.
I want to search document 1 for a specific string. When I locate that string, I want to insert all the content of document 2 in a line after the specific string.
Before insertion:
Document 1 content:
text...
SpecificString
text...
After insertion:
Document 1 content:
text...
SpecificString
Document 2 content
text...
I've been trying different methods, but none are working, and keep deleting all content from document 1 and replacing it. Youtube & Google haven't yielded any desireble results, maybe im just looking in the wrong places.
I tried differnet things, this is 1 example:
f1 = '/Users/Win10/Desktop/Pythonprojects/oldfile.txt'
f2 = '/Users/Win10/Desktop/Pythonprojects/newfile.txt'
searchString=str("<\module>")
with open(f1, "r") as moduleinfo, open(f2, "w") as newproject:
new_contents = newproject.readlines()
#Now prev_contents is a list of strings and you may add the new line to this list at any position
if searchString in f1:
new_contents.insert(0,"\n")
new_contents.insert(0,moduleinfo)
#new_file.write("\n".join(new_contents))
The code simply deleted the content of document 1.
You can find interesting answers (How do I write to the middle of a text file while reading its contents?, Can you write to the middle of a file in python?, Adding lines after specific line)
By the way, an interesting way is to iterate the file in a read mode to find the index where the insert must be. Afterwards, overwrite the file with new indexing:
a) File2 = File2[:key_index] + File1 + File 2[key_index:]
Another option explained by Adding lines after specific line:
with open(file, "r") as in_file:
buf = in_file.readlines()
with open(file, "w") as out_file:
for line in buf:
if line == "YOUR SEARCH\n":
line = line + "Include below\n"
out_file.write(line)
Please tell us your final approach.
KR,
You have to import the second file in append mode instead of writing mode. Write mode override the document. Append mode add text to the end of the file, but you can move the pointer to the wanted location for writing and append the text there.
You can enter append mode by replacing the 'w' with 'a'.
Thanks for your input, it put me on the right track. I ended up going with the following:
f2 = '/Users/Win10/Desktop/Pythonprojects/newfile.txt'
f1 = '/Users/Win10/Desktop/Pythonprojects/oldfile.txt'
with open(f2) as file:
original = file.read()
with open(f1) as input:
myinsert = input.read()
newfile = original.replace("</Module>", "</Module>\n"+myinsert)
with open(f2, "w") as replaced:
replaced.write(newfile)
text from oldfile is inserted into newfile in a new line, under the "/Module" string. I'll be following up, if I find better solutions. Again, thank you for your answers.

Split at every new instance of string Python

I am trying to split some file metadata taken from dropbox at every instance of 'FileMetadata' and write to a text file. It's printing in my console as I need but appending to the text file the new line isn't coming through.
To provide some context to the code I am getting the file meta data and writing it to a file and reading it to then split it.
with open (write_file, 'rt') as read_file:
contents = read_file.read()
data = contents.split('FileMetadata')
print (data)
with open (write_file, 'w') as file1:
file1.write(str(data))
It appears you want a newline for every part that was split by the 'FileMetadata' string.
Instead of your file1.write(str(data)), did you try file1.write("\n".join(data))?

delete all .csv file content in python

so, my program will replace the old data with new data which is the program will put in same .csv file. and after i run the program it is not replaced. below is my code.
TEXTFILE = open("data.csv", "w")
for i in book_list:
TEXTFILE.write("{},{},{},{}".format(i[0],i[1],i[2],i[3]))
TEXTFILE.close()
book_list is the list that save new data to stored
the result i got:
k,k,45,c
a,a,65,r
d,s,65,r
as,as,65,r
df,df6,65,r
as,as,6,r
as,as,46,r
as,as,45,r
as,as,56,rk,k,45,r
a,a,65,r
d,s,65,r
as,as,65,r
df,df6,65,r
as,as,6,r
as,as,46,r
as,as,45,r
as,as,56,r
it stored to csv with combining old and new content.
well the origininal file is looks like this:
k,k,45,r
a,a,65,r
d,s,65,r
as,as,65,r
df,df6,65,r
as,as,6,r
as,as,46,r
as,as,45,r
as,as,56,r
idk how to explain. but I expect that the result will change one line with new data in the fourth row. for example, the previous line is k,k,45,r (line 1). and the program will change it become k,k,45,c that way
hope you all can help me :)
Try using .truncate() , if called after opening file it destroys it's content.
TEXTFILE = open("data.csv", "w")
TEXTFILE.truncate()
for i in book_list:
TEXTFILE.write("{},{},{},{}".format(i[0],i[1],i[2],i[3]))
TEXTFILE.close()
I hope I understood you correctly.

Replace string in specific line of nonstandard text file

Similar to posting: Replace string in a specific line using python, however results were not forethcomming in my slightly different instance.
I working with python 3 on windows 7. I am attempting to batch edit some files in a directory. They are basically text files with .LIC tag. I'm not sure if that is relevant to my issue here. I am able to read the file into python without issue.
My aim is to replace a specific string on a specific line in this file.
import os
import re
groupname = 'Oldtext'
aliasname = 'Newtext'
with open('filename') as f:
data = f.readlines()
data[1] = re.sub(groupname,aliasname, data[1])
f.writelines(data[1])
print(data[1])
print('done')
When running the above code I get an UnsupportedOperation: not writable. I am having some issue writing the changes back to the file. Based on suggestion of other posts, I edited added the w option to the open('filename', "w") function. This causes all text in the file to be deleted.
Based on suggestion, the r+ option was tried. This leads to successful editing of the file, however, instead of editing the correct line, the edited line is appended to the end of the file, leaving the original intact.
Writing a changed line into the middle of a text file is not going to work unless it's exactly the same length as the original - which is the case in your example, but you've got some obvious placeholder text there so I have no idea if the same is true of your actual application code. Here's an approach that doesn't make any such assumption:
with open('filename', 'r') as f:
data = f.readlines()
data[1] = re.sub(groupname,aliasname, data[1])
with open('filename', 'w') as f:
f.writelines(data)
EDIT: If you really wanted to write only the single line back into the file, you'd need to use f.tell() BEFORE reading the line, to remember its position within the file, and then f.seek() to go back to that position before writing.

Reading and writing files python

I am trying to write three separate line in a text document based on input obtained from a dialogue window. I am sure this is a simple fix but I can't seem to write the three lines as separate lines. Would someone mind telling me what's wrong with this bit of code?
file = open('file.txt', 'wb')
file.write('input1')
file.write('input2')
file.write('input3')
The inputs should be on different lines but instead they come out as:
input1input2input3
Instead of:
input1
input2
input3
Try this:
file = open('file.txt', 'wb')
file.write('input1\n')
file.write('input2\n')
file.write('input3\n')
You are appending the newline character '\n' to advance to the next line.
If you use the with construct, it will automatically close the file for you:
with open('file.txt', 'wb') as file:
file.write('input1\n')
file.write('input2\n')
file.write('input3\n')
Also, consider using a different variable name in place of file.
Your issue is that you haven't included newlines. Remember, Python is outputting like a typewriter--you don't tell it to go to a new line, it won't. The way to write a newline is \n.
So,
file.write('\n'.join([input1, input2, input3]))
Would do it.

Categories