In bash, I have a file that stores my passwords in variable format.
e.g.
cat file.passwd
password1=EncryptedPassword1
password2=EncryptedPassword2
Now if I want to use the value of password1, this is all that I need to do in bash.
grep password1 file.passwd | cut -d'=' -f2
I am looking for an alternative for this in python. Is there any library that gives functionality to simply extract the value or do we have to do it manually
like below?
with open(file, 'r') as input:
for line in input:
if 'password1' in line:
re.findall(r'=(\w+)', line)
Read the file and add the check statement:
if line.startswith("password1"):
print re.findall(r'=(\w+)',line)
Code:
import re
with open(file,"r") as input:
lines = input.readlines()
for line in lines:
if line.startswith("password1"):
print re.findall(r'=(\w+)',line)
There's nothing wrong with what you've written. If you want to play code golf:
line = next(line for line in open(file, 'r') if 'password1' in line)
I found this module very useful ! Made life much easier.
Related
Sorry for this very basic question. I am new to Python and trying to write a script which can print the URL links. The IP addresses are stored in a file named list.txt. How should I use the variable in the link? Could you please help?
# cat list.txt
192.168.0.1
192.168.0.2
192.168.0.9
script:
import sys
import os
file = open('/home/list.txt', 'r')
for line in file.readlines():
source = line.strip('\n')
print source
link = "https://(source)/result”
print link
output:
192.168.0.1
192.168.0.2
192.168.0.9
https://(source)/result
Expected output:
192.168.0.1
192.168.0.2
192.168.0.9
https://192.168.0.1/result
https://192.168.0.2/result
https://192.168.0.9/result
You need to pass the actual variable, you can iterate over the file object so you don't need to use readlines and use with to open your files as it will close them automatically. You also need the print inside the loop if you want to see each line and str.rstrip() will remove any newlines from the end of each line:
with open('/home/list.txt') as f:
for ip in f:
print "https://{0}/result".format(ip.rstrip())
If you want to store all the links use a list comprehension:
with open('/home/list.txt' as f:
links = ["https://{0}/result".format(ip.rstrip()) for line in f]
For python 2.6 you have to pass the numeric index of a positional argument, i.e {0} using str.format .
You can also use names to pass to str.format:
with open('/home/list.txt') as f:
for ip in f:
print "https://{ip}/result".format(ip=ip.rstrip())
Get the link inside the loop, you are not appending data to it, you are assigning to it every time. Use something like this:
file = open('/home/list.txt', 'r')
for line in file.readlines():
source = line.strip('\n')
print source
link = "https://%s/result" %(source)
print link
Try this:
lines = [line.strip('\n') for line in file]
for source in lines:
print source
for source in lines:
link = "https://{}/result".format(source)
print link
The feature you just described is often called string interpolation.
In Python, this is called string formatting.
There are two styles of string formatting in Python: the old style and the new style.
What I've shown in the example above is the new style, in which we format with a string method named format.
While the old style uses the % operator, eg. "https://%s/result" % source
Use format specifier for string and also put the link printing section in the for loop only
something like this:
import sys
import os
file = open('/home/list.txt', 'r')
for line in file.readlines():
source = line.strip('\n')
print source
link = "https://%s/result”%source
print link
import sys
import os
file = open('/home/list.txt', 'r')
for line in file.readlines():
source = line.strip('\n')
print source
link = "https://" + str(source) + "/result”
print link
I am trying to write a python script which SSHes into a specific address and dumps a text file. I am currently having some issues. Right now, I am doing this:
temp = "cat file.txt"
need = subprocess.Popen("ssh {host} {cmd}".format(host='155.0.1.1', cmd=temp),shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
print(need)
This is the naive approach where I am basically opening the file, saving its output to a variable and printing it. However, this really messes up the format when I print "need". Is there any way to simply use subprocess and read the file line by line? I have to be SSHed into the address in order to dump the file otherwise the file will not be detected, that is why I am not simply doing
f = open(temp, "r")
file_contents = f.read()
print (file_contents)
f.close()
Any help would be appreciated :)
You don't need to use the subprocess module to print the entire file line by line. You can use pure python.
f = open(temp, "r")
file_contents = f.read()
f.close()
# turn the file contents into a list
file_lines = file_contents.split("\n")
# print all the items in the list
for file_line in file_lines:
print(file_line)
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'.
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")
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")