Not able to clear file Contents - python

I have a file which has below data.
edit 48
set dst 192.168.4.0 255.255.255.0
set device "Tague-VPN"
set comment "Yeshtel"
edit 180
set dst 64.219.107.45 255.255.255.255
set device "Austin-Backup"
set comment "images.gsmc.org"
I want to copy the commands under edit only if Set device is Austin-Backup.
string = 'set device'
word = '"Austin-Backup"'
with open('test.txt') as oldfile, open('script.txt', 'w') as newfile:
for line in oldfile:
newfile.write(line)
newfile.write('\n')
if string not in line:
pass
elif string in line:
if word not in line:
a = open('script.txt', 'w')
a.close()
else:
pass
I am trying to write test file content to new file(script) and if command "set comment "Yeshtel"" is found i want to delete contents in new file. I tried to delete but its not happening. I am new to Python, Can you please tell what is the Prob??
I got to know that reopening the same file in Write mode will clear the contents..

I suspect the issue is that you have the same file open twice, once as newfile and a second time as a. While it should be truncated when you open it as a and then close it, the writes you made on newfile may still appear if the filesystem had cached them until after the truncated version was written.
I suggest only opening the file once. When you need to truncate it, call the truncate method on it.
if word not in line:
newfile.truncate()
If you might write more to the file after truncating, you should probably also seek back to the start position (e.g. newfile.seek(0)). If you're going to be done with the file after truncating it, that step is not needed.

Should be something like this
temp_lines = []
last_line_was_edit = False
found_keyword = False
keyword = "Austin-Backup"
with open('test.txt') as oldfile, open('script.txt', 'w') as newfile:
for line in oldfile:
if last_line_was_edit and temp_lines:
if found_keyword:
newfile.writelines(temp_lines)
temp_lines = []
if line.startswith("edit"):
last_line_was_edit = True
else:
if keyword in line:
found_keyword = True
temp_lines.append(line)
Please note that you should not open the file twice. Just use an temporary variable and write only what have to be written

Related

How to find first and last characters in a file using python?

I am stuck on this revision exercise which asks to copy an input file to an output file and return the first and last letters.
def copy_file(filename):
input_file = open(filename, "r")
content = input_file.read()
content[0]
content[1]
return content[0] + content[-1]
input_file.close()
Why do I get an error message which I try get the first and last letters? And how would I copy the file to the output file?
Here is the test:
input_f = "FreeAdvice.txt"
first_last_chars = copy_file(input_f)
print(first_last_chars)
print_content('cure737.txt')
Error Message:
FileNotFoundError: [Errno 2] No such file or directory: 'hjac737(my username).txt'
All the code after a return statement is never executed, a proper code editor would highlight it to you, so I recommend you use one. So the file was never closed. A good practice is to use a context manager for that : it will automatically call close for you, even in case of an exception, when you exit the scope (indentation level).
The code you provided also miss to write the file content, which may be causing the error you reported.
I explicitely used the "rt" (and "wt") mode for the files (althought they are defaults), because we want the first and last character of the file, so it supports Unicode (any character, not just ASCII).
def copy_file(filename):
with open(filename, "rt") as input_file:
content = input_file.read()
print(input_file.closed) # True
my_username = "LENORMJU"
output_file_name = my_username + ".txt"
with open(output_file_name, "wt") as output_file:
output_file.write(content)
print(output_file.closed) # True
# last: return the result
return content[0] + content[-1]
print(copy_file("so67730842.py"))
When I run this script (on itself), the file is copied and I get the output d) which is correct.

Bulk autoreplacing string in the KML file

I have a set of placemarks, which include quite a wide description included in its balloon within the property. Next each single description (former column header) is bounded in . Because of the shapefile naming restriction to 10 characters only.
https://gis.stackexchange.com/questions/15784/bypassing-10-character-limit-of-field-name-in-shapefiles
I have to retype most of these names manually.
Obviously, I use Notepad++, where I can swiftly press Ctrl+F and toggle Replace mode, as you can see below.
The green bounded strings were already replaced, the red ones still remain.
Basically, if I press "Replace All" then it works fine and quickly. Unfortunately, I have to go one by one. As you can see I have around 20 separate strings to "Replace all". Is there a possibility to do it quicker? Because all the .kml files are similar to each other, this is going to be the same everywhere. I need some tool, which will be able to do auto-replace for these headers cut by 10 characters limit. I think, that maybe Python tools might be helpful.
https://pythonhosted.org/pykml/
But in the tool above there is no information about bulk KML editing.
How can I set something like the "Replace All" tool for all my strings preferably if possible?
UPDATE:
I tried the code below:
files = []
with open("YesNF016.kml") as f:
for line in f.readlines():
if line[-1] == '\n':
files.append(line[:-1])
else:
files.append(line)
old_expression = 'ab'
new_expression = 'it worked'
for file in files:
new_file = ""
with open(file) as f:
for line in f.readlines():
new_file += line.replace(old_expression, new_expression)
with open(file, 'w') as f:
f.write(new_file)
The debugger shows:
[Errno 22] Invalid argument: ''
File "\test.py", line 13, in
with open(file) as f:
whereas line 13 is:
with open(file) as f:
The solutions here:
https://www.reddit.com/r/learnpython/comments/b9cljd/oserror_while_using_elementtree_to_parse_simple/
and
OSError: [Errno 22] Invalid argument Getting invalid argument while parsing xml in python
weren't helpful enough for me.
So you want to replace all occurence of X to Y in bunch of files ?
Pretty easy.
Just create a file_list.txt containing the list of files to edit.
python code:
files = []
with open("file_list.txt") as f:
for line in f.readlines():
if line[-1] == '\n':
files.append(line[:-1])
else:
files.append(line)
old_expression = 'ab'
new_expression = 'it worked'
for file in files:
new_file = ""
with open(file) as f:
for line in f.readlines():
new_file += line.replace(old_expression, new_expression)
with open(file, 'w') as f:
f.write(new_file)

Python delete line and write over it

i have proplem here with my code
i am using for loop to save results in txt file
every time i use it it's saving the last line and delete the old line
here is code:
for i in domains:
requests.get(i)
if req.status_code == 200:
print('[+]:', i + '/')
file = open(save,'w')
file.write(domain)
file.close()
so after run the code it's save the last domain or last results and delete the old results
so i want solution
thanks.
Open the file in append mode:
open(filename,'a')
Your code should be:
for i in domains:
requests.get(i)
if req.status_code == 200:
print('[+]:', i + '/')
file = open(save,'a')
file.write(i)
file.close()
Try open it with a instead of w, so:
file = open(save, 'a')
it should appends to the file instead of writing to it
You sould use 'a' instead of 'w' in "file = open(save,'w')"
The problem here is arising because you are opening the file for writing on every iteration of the loop. Because you are opening the file with mode 'w', the file is being overwritten every time. (See documentation.)
It would be better to open the file once only, outside the loop.
For example:
file = open(save, 'w')
for i in domains:
# do some stuff...
file.write(some_data)
file.close()
You can also use with in conjuction with the open function:
with open(save, 'w') as file:
for i in domains:
# do some stuff...
file.write(some_data)
In this case, there is no need for an explicit call to file.close(). This will be done automatically when the loop ends, or even if something happens inside the with block like an exception being raised (i.e. error occurring) or a return from the function (if applicable).
Be aware that because of output buffering, data written to the file during one iteration might not actually get written to the file until some later iteration or after the file is closed. If this would be a problem, then you can insert a flush call to force a low-level write so that other processes can see the data:
with open(save, 'w') as file:
for i in domains:
# do some stuff...
file.write(some_data)
file.flush()
If there is some reason why you need to open the file inside the loop, then you could open it in append mode using 'a', and the data will be written after the end of the existing file. (Again, see the documentation linked earlier.) For example:
for i in domains:
# do some stuff...
file = open(save, 'a')
file.write(some_data)
file.close()
or again, better like this:
for i in domains:
with open(save, 'a') as file:
# do some stuff...
file.write(some_data)
Be aware that if the output file already exists before the program is started, then the contents of the existing file will remain because you are always opening it in append mode. Depending on your application, this might or might not be desirable.

How to write integer to a file,.io.UnsupportedOperation: not writable

I'm trying to add 1 to the last integer of a file in excel. I can do this as the new_id is correct. However when I try to write the new_id to the file it does not work. Returning the io.UnsupportedOperation: not writable error message.
import csv
ID = []
file = open("customerID.csv","r")
for x in file:
ID.append(x)
lastid = int(ID[-1])
new_id = (lastid + 1)
file.close
print(lastid)
print (new_id)
file.write (str(new_id))
file.close
You opened the file for reading only when you specified 'r' in open. If you want to be able to write, you need to open it for writing. Use either 'a' if you want to write to the end of the file (appending), or 'w' if you want to erase the file prior to writing:
file = open("customerID.csv", "a")
Also note, your file.close lines aren't doing anything. You need to actually call the close method:
file.close() # Note the ()
And, you can't use file once close has been called on it.

string.replace method in python

I am a newbie with python, so kindly excuse for asking basic question.
I am trying to use the string.replace method in python and getting a weird behavior. here is what I am doing:
# passing through command line a file name
with open(sys.argv[2], 'r+') as source:
content = source.readlines()
for line in content:
line = line.replace(placeholerPattern1Replace,placeholerPattern1)
#if I am printing the line here, I am getting the correct value
source.write(line.replace(placeholerPattern1Replace,placeholerPattern1))
try:
target = open('baf_boot_flash_range_test_'+subStr +'.gpj', 'w')
for line in content:
if placeholerPattern3 in line:
print line
target.write(line.replace(placeholerPattern1, <variable>))
target.close()
When I am checking the values in the new file, then these are not replaced. I could see that the value of the source is also not changed, but the content had changed, what am I doing wrong here?
Rather do something like this -
contentList = []
with open('somefile.txt', 'r') as source:
for line in source:
contentList.append(line)
with open('somefile.txt','w') as w:
for line in contentList:
line = line.replace(stringToReplace,stringToReplaceWith)
w.write(line)
Because with will close your file after runing all the statements wrapped within it, which means the content local variable will be nil in the second loop.
You are reading from the file source and also writing to it. Don't do that. Instead, you should write to a NamedTemporaryFile and then rename it over the original file after you finish writing and close it.
Try this:
# Read the file into memory
with open(sys.argv[2], 'r') as source:
content = source.readlines()
# Fix each line
new_content = list()
for line in content:
new_content.append(line.replace(placeholerPattern1Replace, placeholerPattern1))
# Write the data to a temporary file name
with open(sys.argv[2] + '.tmp', 'w') as dest:
for line in new_content:
dest.write(line)
# Rename the temporary file to the input file name
os.rename(sys.argv[2] + '.tmp', sys.argv[2])

Categories

Resources