I want to replace word after finding a specific word in a file using python. I tried re.replace or re.sub function but does not get help.
File Contents :
hostname: "abc-myvm-lx01"
I want to keep "hostname: " as static and replace rest of values.
After replacement file will be look like :
hostname: "abc-urvm-lx02"
How about parsing the file yourself:
# READ ENTRIES FROM FILE
entries = {}
with open('your_file.txt', 'r') as file:
for line in file:
entry = line.split(':')
# Allow values like abc:myvm:lx01
entries[entry[0]] = ':'.join(entry[1:]).strip()
# Modify entries['hostname'] in any way you want
# WRITE ENTRIES TO FILE
with open('your_file.txt', 'w') as file:
file.writelines('{}: {}\n'.format(*entry) for entry in entries.items())
Related
Please help I need python to compare text line(s) to words like this.
with open('textfile', 'r') as f:
contents = f.readlines()
print(f_contents)
if f_contents=="a":
print("text")
I also would need it to, read a certain line, and compare that line. But when I run this program it does not do anything no error messages, nor does it print text. Also
How do you get python to write in just line 1? When I try to do it for some reason, it combines both words together can someone help thank you!
what is f_contents it's supposed to be just print(contents)after reading in each line and storing it to contents. Hope that helps :)
An example of reading a file content:
with open("criticaldocuments.txt", "r") as f:
for line in f:
print(line)
#prints all the lines in this file
#allows the user to iterate over the file line by line
OR what you want is something like this using readlines():
with open("criticaldocuments.txt", "r") as f:
contents = f.readlines()
#readlines() will store each and every line into var contents
if contents == None:
print("No lines were stored, file execution failed most likely")
elif contents == "Password is Password":
print("We cracked it")
else:
print(contents)
# this returns all the lines if no matches
Note:
contents = f.readlines()
Can be done like this too:
for line in f.readlines():
#this eliminates the ambiguity of what 'contents' is doing
#and you could work through the rest of the code the same way except
#replace the contents with 'line'.
def Delete_con():
contact_to_delete= input("choose name to delete from contact")
to_Delete=list(contact_to_delete)
with open("phonebook1.txt", "r+") as file:
content = file.read()
for line in content:
if not any(line in line for line in to_Delete):
content.write(line)
I get zero error. but the line is not deleted. This function ask the user what name he or she wants to delete from the text file.
This should help.
def Delete_con():
contact_to_delete= input("choose name to delete from contact")
contact_to_delete = contact_to_delete.lower() #Convert input to lower case
with open("phonebook1.txt", "r") as file:
content = file.readlines() #Read lines from text
content = [line for line in content if contact_to_delete not in line.lower()] #Check if user input is in line
with open("phonebook1.txt", "w") as file: #Write back content to text
file.writelines(content)
Assuming that:
you want the user to supply just the name, and not the full 'name:number' pair
your phonebook stores one name:number pair per line
I'd do something like this:
import os
from tempfile import NamedTemporaryFile
def delete_contact():
contact_name = input('Choose name to delete: ')
# You probably want to pass path in as an argument
path = 'phonebook1.txt'
base_dir = os.path.dirname(path)
with open(path) as phonebook, \
NamedTemporaryFile(mode='w+', dir=base_dir, delete=False) as tmp:
for line in phonebook:
# rsplit instead of split supports names containing ':'
# if numbers can also contain ':' you need something smarter
name, number = line.rsplit(':', 1)
if name != contact_name:
tmp.write(line)
os.replace(tmp.name, path)
Using a tempfile like this means that if something goes wrong while processing the file you aren't left with a half-written phonebook, you'll still have the original file unchanged. You're also not reading the entire file into memory with this approach.
os.replace() is Python 3.3+ only, if you're using something older you can use os.rename() as long as you're not using Windows.
Here's the tempfile documentation. In this case, you can think of NamedTemporaryFile(mode='w+', dir=base_dir, delete=False) as something like open('tmpfile.txt', mode='w+'). NamedTemporaryFile saves you from having to find a unique name for your tempfile (so that you don't overwrite an existing file). The dir argument creates the tempfile in the same directory as phonebook1.txt which is a good idea because os.replace() can fail when operating across two different filesystems.
def codeOnly (file):
'''Opens a file and prints the content excluding anything with a hash in it'''
f = open('boring.txt','r')
codecontent = f.read()
print(codecontent)
codeOnly('boring.txt')
I want to open this file and print the contents of it however i don't want to print any lines with hashes in them. Is there a function to prevent these lines from being printed?
The following script with print all lines which do not contain a #:
def codeOnly(file):
'''Opens a file and prints the content excluding anything with a hash in it'''
with open(file, 'r') as f_input:
for line in f_input:
if '#' not in line:
print(line, end='')
codeOnly('boring.txt')
Using with will ensure that the file is automatically closed afterwards.
You can check if the line contains a hash with not '#' in codecontent (using in):
def codeOnly (file):
'''Opens a file and prints the content excluding anything with a hash in it'''
f = open('boring.txt','r')
for line in f:
if not '#' in line:
print(line)
codeOnly('boring.txt')
If you really want to keep only code lines, you might want to keep the part of the line until the hash, because in languages such as python you could have code before the hash, for example:
print("test") # comments
You can find the index
for line in f:
try:
i = line.index('#')
line = line[:i]
except ValueError:
pass # don't change line
Now each of your lines will contain no text from and including the hash tag until the end of the line. Hash tags in the first position of a line will result in an empty string, you might want to handle that.
I'm writing a script I can use at work for bulk lotus note user registration.
Basically I need to manipulate a text file that contains a list of usernames into a file i can import into domino administrator.
For example I have a text file that contains,
Gordan.Freeman
Gordan.Freeman1
Gordan.Freeman2
And I need to get it looking like
Freeman;Gordan;;;12345678;D:\lotus\NotesIDs\Users\;GordanFreeman.id;SERVER01;mail\users\;GordanFreeman.nsf;;;;;;;;;;template.ntf;
Freeman1;Gordan;;;12345678;D:\lotus\NotesIDs\Users\;GordanFreeman1.id;SERVER01;mail\users\;GordanFreeman1.nsf;;;;;;;;;;template.ntf;
Freeman2;Gordan;;;12345678;D:\lotus\NotesIDs\Users\;GordanFreeman2.id;SERVER01;mail\users\;GordanFreeman2.nsf;;;;;;;;;;template.ntf;
I've only gotten as far as reading from the text file into a list, but from what i can tell I need to convert it back into a string before i can write to a new text file.
textloc = input(r" Enter the file path of your list (eg.'C:\names_list.txt) --> ")
textopen = open(textloc, 'r')
nameslistraw = textopen.read().split('\n')
nameslist = [i.split('.') for i in nameslistraw]
I've been fiddling around with this for hours. Any help would be great :)
Here is a working script that does what you appear to want.
file = open('myfile.txt', 'r')
temp = []
for line in file:
item = line.strip('\n').split('.')
temp.append(';'.join(item[::-1])+';'*3+'12345678;D:\lotus\NotesIDs\Users\;'+''.join(item)+'.id;SERVER01;mail\users\;'+''.join(item)+'.nsf;;;;;;;;;;template.ntf;')
file.close()
file = open('myfile.txt', 'w')
file.write('\n'.join(temp))
file.close()
Which transforms the following:
Gordan.Freeman
Gordan.Freeman1
Gordan.Freeman2
Into:
Freeman;Gordan;;;12345678;D:\lotus\NotesIDs\Users\;GordanFreeman.id;SERVER01;mail\users\;GordanFreeman.nsf;;;;;;;;;;template.ntf;
Freeman1;Gordan;;;12345678;D:\lotus\NotesIDs\Users\;GordanFreeman1.id;SERVER01;mail\users\;GordanFreeman1.nsf;;;;;;;;;;template.ntf;
Freeman2;Gordan;;;12345678;D:\lotus\NotesIDs\Users\;GordanFreeman2.id;SERVER01;mail\users\;GordanFreeman2.nsf;;;;;;;;;;template.ntf;
I should preface that I am a complete Python Newbie.
Im trying to create a script that will loop through a directory and its subdirectories looking for text files. When it encounters a text file it will parse the file and convert it to NITF XML and upload to an FTP directory.
At this point I am still working on reading the text file into variables so that they can be inserted into the XML document in the right places. An example to the text file is as follows.
Headline
Subhead
By A person
Paragraph text.
And here is the code I have so far:
with open("path/to/textFile.txt") as f:
#content = f.readlines()
head,sub,auth = [f.readline().strip() for i in range(3)]
data=f.read()
pth = os.getcwd()
print head,sub,auth,data,pth
My question is: how do I iterate through the body of the text file(data) and wrap each line in HTML P tags? For example;
<P>line of text in file </P> <P>Next line in text file</p>.
Something like
output_format = '<p>{}</p>\n'.format
with open('input') as fin, open('output', 'w') as fout:
fout.writelines( output_format(line.strip()) for line in fin )
This assumes that you want to write the new content back to the original file:
with open('path/to/textFile.txt') as f:
content = f.readlines()
with open('path/to/textFile.txt', 'w') as f:
for line in content:
f.write('<p>' + line.strip() + '</p>\n')
with open('infile') as fin, open('outfile',w) as fout:
for line in fin:
fout.write('<P>{0}</P>\n'.format(line[:-1]) #slice off the newline. Same as `line.rstrip('\n')`.
#Only do this once you're sure the script works :)
shutil.move('outfile','infile') #Need to replace the input file with the output file
in you case, you should probably replace
data=f.read()
with:
data = '\n'.join("<p>%s</p>" % l.strip() for l in f)
use data=f.readlines() here,
and then iterate over data and try something like this:
for line in data:
line="<p>"+line.strip()+"</p>"
#write line+'\n' to a file or do something else
append the and <\p> for each line
ex:
data_new=[]
data=f.readlines()
for lines in data:
data_new.append("<p>%s</p>\n" % data.strip().strip("\n"))
You could use the fileinput module to modify one or more files in-place, with optional backup file creation if desired (see its documentation for details). Here's it being used to process one file.
import fileinput
for line in fileinput.input('testinput.txt', inplace=1):
print '<P>'+line[:-1]+'<\P>'
The 'testinput.txt' argument could also be a sequence of two or more file names instead of just a single one, which could be useful especially if you're using os.walk() to generate the list of files in the directory and its subdirectories to process (as you probably should be doing).