I have a quick and dirty build script that needs to update a couple of lines in a small xml config file. Since the file is so small, I'm using an admittedly inefficient process to update the file in place just to keep things simple:
def hide_osx_dock_icon(app):
for line in fileinput.input(os.path.join(app, 'Contents', 'Info.plist'), inplace=True):
line = re.sub(r'(<key>CFBundleDevelopmentRegion</key>)', '<key>LSUIElement</key><string>1</string>\g<1>', line.strip(), flags=re.IGNORECASE)
print line.strip()
The idea is to find the <key>CFBundleDevelopmentRegion</key> text and insert the LSUIElement content right in front of it. I'm doing something just like this in another area and it's working fine so I guess I'm just missing something, but I don't see it.
What am I doing wrong?
You are printing only the last line, because your print statement falls outside of the for loop:
for line in fileinput.input(os.path.join(app, 'Contents', 'Info.plist'), inplace=True):
line = re.sub(r'(<key>CFBundleDevelopmentRegion</key>)', '<key>LSUIElement</key><string>1</string>\g<1>', line.strip(), flags=re.IGNORECASE)
print line.strip()
Indent that line to match the previous:
for line in fileinput.input(os.path.join(app, 'Contents', 'Info.plist'), inplace=True):
line = re.sub(r'(<key>CFBundleDevelopmentRegion</key>)', '<key>LSUIElement</key><string>1</string>\g<1>', line.strip(), flags=re.IGNORECASE)
print line.strip()
Related
I am currently parsing an xml file to find the a pattern and extract what i need from inside it.
is there a way so that when i find the line i am looking for to count two lines down and grab that line.
with open(filepath) as f:
for line in f:
if pattern.search(line):
#parse each line returned and return only the host names
result = re.findall('"([^"]*)"',line )
print(result)
example xml
<Computer3Properties name="UH25">
<Description property="Description">
<DescriptionValue value="lab" type="VTR" />
output
UH25
Desired output
UH25
lab
now i cant reparse the file and look for the pattern because there are many instances of
<DescriptionValue value=
so i have to grab it once i find the hostname go down the rows and scrape the data inside value
I created an example.xml file containing the exact example contents you specified:
<Computer3Properties name="UH25">
<Description property="Description">
<DescriptionValue value="lab" type="VTR" />
This code:
import re
pattern = "UH25"
with open("path","r") as file:
for line in file:
if re.search(pattern,line):
file.readline()
print(file.readline())
will print whichever line comes two lines after the line where the pattern match was found. Using the example file, you get ''. The reason why this prints two lines down is that the readline() method will grab the contents of the next line. Using it two times (as I did) will print the second line from the line with the match. You said your desired output was specifically printing 'lab' from this line. If so, only the print() line needs to be slightly modified:
import re
pattern = "UH25"
hostnames = []
with open("path","r") as file:
for line in file:
if re.search(pattern,line):
hostnames += re.findall(pattern,line)
file.readline()
hostnames.append(file.readline().split('"')[1])
for x in hostnames:
print(x)
For example, we have some file like that:
first line
second line
third line
And in result we have to get:
first line
second line
third line
Use ONLY python
The with statement is excellent for automatically opening and closing files.
with open('myfile','rw') as file:
for line in file:
if not line.isspace():
file.write(line)
import fileinput
for line in fileinput.FileInput("file",inplace=1):
if line.rstrip():
print line
import sys
with open("file.txt") as f:
for line in f:
if not line.isspace():
sys.stdout.write(line)
Another way is
with open("file.txt") as f:
print "".join(line for line in f if not line.isspace())
with open(fname, 'r+') as fd:
lines = fd.readlines()
fd.seek(0)
fd.writelines(line for line in lines if line.strip())
fd.truncate()
I know you asked about Python, but your comment about Win and Linux indicates that you're after cross-platform-ness, and Perl is at least as cross-platform as Python. You can do this easily with one line of Perl on the command line, no scripts necessary: perl -ne 'print if /\S/' foo.txt
(I love Python and prefer it to Perl 99% of the time, but sometimes I really wish I could do command-line scripts with it as you can with the -e switch to Perl!)
That said, the following Python script should work. If you expect to do this often or for big files, it should be optimized with compiling the regular expressions too.
#!/usr/bin/python
import re
file = open('foo.txt', 'r')
for line in file.readlines():
if re.search('\S', line): print line,
file.close()
There are lots of ways to do this, that's just one :)
>>> s = """first line
... second line
...
... third line
... """
>>> print '\n'.join([i for i in s.split('\n') if len(i) > 0])
first line
second line
third line
>>>
You can use below way to delete all blank lines:
with open("new_file","r") as f:
for i in f.readlines():
if not i.strip():
continue
if i:
print i,
We can also write the output to file using below way:
with open("new_file","r") as f, open("outfile.txt","w") as outfile:
for i in f.readlines():
if not i.strip():
continue
if i:
outfile.write(i)
Have you tried something like the program below?
for line in open(filename):
if len(line) > 1 or line != '\n':
print(line, end='')
Explanation: On Linux/Windows based platforms where we have shell installed below solution may work as "os" module will be available and trying with Regex
Solution:
import os
os.system("sed -i \'/^$/d\' file.txt")
I'm trying to get a python script to read the contents of a text file and if it's 21 turn on a LED but if it's 20 turn it off. The script also prints out the contents of the text file on the screen.
The contents print out works all ok but the LED does not turn on.
import wiringpi2
import time
wiringpi2.wiringPiSetupGpio()
wiringpi2.pinMode(17,1)
while 1:
fh=open("test1.txt","r")
print fh.read()
line = fh.read()
fh.close()
if line == "21":
wiringpi2.digitalWrite(17,1)
elif line == "20":
wiringpi2.digitalWrite(17,0)
time.sleep(2)
print fh.read()
reads the entire contents of the file, leaving the file cursor at the end of the file, so when you do
line = fh.read()
there's nothing left to read.
Change this:
fh=open("test1.txt","r")
print fh.read()
line = fh.read()
fh.close()
to this:
fh=open("test1.txt","r")
line = fh.read()
print line
fh.close()
I can't test this code, since I don't have a Raspberry Pi, but that code will ensure that line contains the entire contents of the text file. That might not actually be desirable: if the file contains any whitespace, eg blank spaces or newlines, then your if ... else tests won't behave like you want. You can fix that by doing
line = line.strip()
after line = fh.read()
The .strip method strips off any leading or trailing whitespace. You can also pass it an argument to tell it what to strip, see the docs for details.
I want to read file including spaces in each lines
My current code
def data():
f = open("save.aln")
for line in f.readlines():
print "</br>"
print line
I am using python and output embedded in html
File to be read - http://pastebin.com/EaeKsyvg
Thanks
It seems that your problem is that you need space preserving in HTML. The simple solution would be to put your output between <pre> elemenets
def data():
print "<pre>"
f = open("save.aln")
for line in f.readlines():
print line
print "</pre>"
Note that in this case you don't need the <br> elements either, since the newline characters are also preserved.
The problem that you are faced with is that HTML ignores multiple whitespaces. #itsadok's solution is great. I upvoted it. But, it's not the only way to do this either.
If you want to explicitly turn those whitespaces into HTML whitespace characters, you could to this:
def data():
f = open("save.aln")
for line in f.readlines():
print "<br />"
print line.replace(" ", " ")
Cheers
import cgi
with open('save.aln') as f:
for line in f:
print cgi.escape(line) # escape <, >, &
print '<br/>'
For example, we have some file like that:
first line
second line
third line
And in result we have to get:
first line
second line
third line
Use ONLY python
The with statement is excellent for automatically opening and closing files.
with open('myfile','rw') as file:
for line in file:
if not line.isspace():
file.write(line)
import fileinput
for line in fileinput.FileInput("file",inplace=1):
if line.rstrip():
print line
import sys
with open("file.txt") as f:
for line in f:
if not line.isspace():
sys.stdout.write(line)
Another way is
with open("file.txt") as f:
print "".join(line for line in f if not line.isspace())
with open(fname, 'r+') as fd:
lines = fd.readlines()
fd.seek(0)
fd.writelines(line for line in lines if line.strip())
fd.truncate()
I know you asked about Python, but your comment about Win and Linux indicates that you're after cross-platform-ness, and Perl is at least as cross-platform as Python. You can do this easily with one line of Perl on the command line, no scripts necessary: perl -ne 'print if /\S/' foo.txt
(I love Python and prefer it to Perl 99% of the time, but sometimes I really wish I could do command-line scripts with it as you can with the -e switch to Perl!)
That said, the following Python script should work. If you expect to do this often or for big files, it should be optimized with compiling the regular expressions too.
#!/usr/bin/python
import re
file = open('foo.txt', 'r')
for line in file.readlines():
if re.search('\S', line): print line,
file.close()
There are lots of ways to do this, that's just one :)
>>> s = """first line
... second line
...
... third line
... """
>>> print '\n'.join([i for i in s.split('\n') if len(i) > 0])
first line
second line
third line
>>>
You can use below way to delete all blank lines:
with open("new_file","r") as f:
for i in f.readlines():
if not i.strip():
continue
if i:
print i,
We can also write the output to file using below way:
with open("new_file","r") as f, open("outfile.txt","w") as outfile:
for i in f.readlines():
if not i.strip():
continue
if i:
outfile.write(i)
Have you tried something like the program below?
for line in open(filename):
if len(line) > 1 or line != '\n':
print(line, end='')
Explanation: On Linux/Windows based platforms where we have shell installed below solution may work as "os" module will be available and trying with Regex
Solution:
import os
os.system("sed -i \'/^$/d\' file.txt")