How to grab all the lines with readline function in python? - python

grabc is a tool for output the colour code and RGB value.
When I use it, the output looks like this.
$grabc
'#000051'
'0,0,81'
I used this program for grabbing the output
import os
p=os.popen('grabc')
s=p.readline()
p.close()
print "a="+s
>>> "a=#000051"
but I want
>>> "a=#000051
0,0,81"
as the output
what should I do to grab the second line.
I am using python. And I need to grab the whole output in a.

One way would be to use lines = p.readlines() instead. This will read not one, but all the lines from the output and return them as a list of strings. However, instead of os.popen you may want to use the corresponding functions of the newer subprocess module instead.
You can use "".join(lines) to join the list of strings to a single string. Since the lines still have their original line end character, you can just use "" as delimiter. Alternatively, you could strip the line end characters and use your own delimiter: "\n".join([l.strip() for l in lines]).
Also, note that you do not assign the output to the variable a at all, but just print it that way. Further, depending on what you want to do with the color values, it might be better to leave them separate and assign them to different variables instead.
Update: On closer inspection, it seems that not all the output of grabc is captured this way, neither with subprocess or even when doing grabc > some_file. The hex-string is captured, but the color tuple is not. However, you can easily convert one value into the other, so this should not be a problem.
h = "#a7bd7a"
t = 167,189,122
"#%02x%02x%02x" % t # color tuple to hex string
[int(h[i:i+2], 16) for i in range(1, len(h), 2)] # hex string to color tuple

Related

Replace words in list that later will be used in variable

I have a file which currently stores a string eeb39d3e-dd4f-11e8-acf7-a6389e8e7978
which I am trying to pass into as a variable to my subprocess command.
My current code looks like this
with open(logfilnavn, 'r') as t:
test = t.readlines()
print(test)
But this prints ['eeb39d3e-dd4f-11e8-acf7-a6389e8e7978\n'] and I don't want the part with ['\n'] to be passed into my command, so i'm trying to remove them by using replace.
with open(logfilnavn, 'r') as t:
test = t.readlines()
removestrings = test.replace('[', '').replace('[', '').replace('\\', '').replace("'", '').replace('n', '')
print(removestrings)
I get an exception value saying this so how can I replace these with nothing and store them as a string for my subprocess command?
'list' object has no attribute 'replace'
so how can I replace these with nothing and store them as a string for my subprocess command?
readline() returns a list. Try print(test[0].strip())
You can read the whole file and split lines using str.splitlines:
test = t.read().splitlines()
Your test variable is a list, because readlines() returns a list of all lines read.
Since you said the file only contains this one line, you probably wish to perform the replace on only the first line that you read:
removestrings = test[0].replace('[', '').replace('[', '').replace('\\', '').replace("'", '').replace('n', '')
Where you went wrong...
file.readlines() in python returns an array (collection or grouping of the same variable type) of the lines in the file -- arrays in python are called lists. you, here are treating the list as a string. you must first target the string inside it, then apply that string-only function.
In this case however, this would not work as you are trying to change the way the python interpretter has displayed it for one to understand.
Further information...
In code it would not be a string - we just can't easily understand the stack, heap and memory addresses easily. The example below would work for any number of lines (but it will only print the first element) you will need to change that and
this may be useful...
you could perhaps make the variables globally available (so that other parts of the program can read them
more useless stuff
before they go out of scope - the word used to mean the points at which the interpreter (what runs the program) believes the variable is useful - so that it can remove it from memory, or in much larger programs only worry about the locality of variables e.g. when using for loops i is used a lot without scope there would need to be a different name for each variable in the whole project. scopes however get specialised (meaning that if a scope contains the re-declaration of a variable this would fail as it is already seen as being one. an easy way to understand this might be to think of them being branches and the connections between the tips of branches. they don't touch along with their variables.
solution?
e.g:
with open(logfilenavn, 'r') as file:
lines = file.readlines() # creates a list
# an in-line for loop that goes through each item and takes off the last character: \n - the newline character
#this will work with any number of lines
strippedLines = [line[:-1] for line in lines]
#or
strippedLines = [line.replace('\n', '') for line in lines]
#you can now print the string stored within the list
print(strippedLines[0]) # this prints the first element in the list
I hope this helped!
You get the error because readlines returns a list object. Since you mentioned in the comment that there is just one line in the file, its better to use readline() instead,
line = "" # so you can use it as a variable outside `with` scope,
with open("logfilnavn", 'r') as t:
line = t.readline()
print(line)
# output,
eeb39d3e-dd4f-11e8-acf7-a6389e8e7978
readlines will return a list of lines, and you can't use replace with a list.
If you really want to use readlines, you should know that it doesn't remove the newline character from the end, you'll have to do it yourself.
lines = [line.rstrip('\n') for line in t.readlines()]
But still, after removing the newline character yourself from the end of each line, you'll have a list of lines. And from the question, it looks like, you only have one line, you can just access first line lines[0].
Or you can just leave out readlines, and just use read, it'll read all of the contents from the file. And then just do rstrip.
contents = t.read().rstrip('\n')

cleaning the format of the printed data in python

I am trying to compare two lists in python and produce two arrays that contain matching rows and non-matching rows, but the program prints the data in an ugly format. How can I clean I go about cleaning it up?
If you want to read the file without the \n character, you might consider doing the following
lines = list1.readlines()
lines2 = list2.readlines()
would read your file without the "\n" characters
Alternatively, for each line, you can do .strip("\n")
The "ugly format" might be because you are using print(match) (which is actually translated by Python to print ( repr(match) ), printing something that is more useful for debugging or as input back to Python - but not 'nice'.
If you want it printed 'nicely', you'd have to decide what format that would be and write the code for it. In the simplest case, you might do:
for i in match:
print(i)
(note your original list contains \n characters, that's what enumerating an open text file does. They will get printed, as well (together with the `\n' added by print() itself). I don't know if you want them removed or not. See the other answer for possible ways of getting rid of them.

How to avoid the last comma while writing an integer array into a text file in python

I need to write an array of integers into a text file, but the formatted solution is adding the comma after each item and I'd like to avoid the last one.
The code looks like this:
with open(name, 'a+') as f:
line = ['FOO ', description, '|Bar|']
f.writelines(line)
f.writelines("%d," % item for item in values)
f.writelines('\n')
Each line starts with a small description of what the array to follow contains, and then a list of integers. New lines are added in the loop as they become available.
The output I get looks something like this:
FOO description|Bar|274,549,549,824,824,824,824,824,794,765,765,736,736,736,736,736,
And I would like to have it look like this, without the last comma:
FOO description|Bar|274,549,549,824,824,824,824,824,794,765,765,736,736,736,736,736
I was unable to find a solution that would work with the writelines() and I need to avoid lengthy processing in additional loops.
Use join:
f.writelines(",".join(map(str,values)))
Note that values is first mapped to a list of strings, instead of numbers, with map.
You can slice it with using below example.
It will always delete last character.
line = ['FOO ', description, '|Bar|']
line = line[:-1]
f.writelines(line)
Slicing is the best approach and works well for every situation atleast in your case.
f.writelines(line[:-1])
You can use print function here.
print(*values,sep=',',file=f)
If you are using python2 please import print function.
from __future__ import print_function

Importing a text file to create a list in Python 3.x?

I can't seem to figure out how to use values given in a text file and import them into python to create a list. What I'm trying to accomplish here is to create a gameboard and then put numbers on it as a sample set. I have to use Quickdraw to accomplish this - I kind of know how to get the numbers on Quickdraw but I cannot seem to import the numbers from the text file. Previous assignments involved getting the user to input values or using an I/O redirection, this is a little different. Could anyone assist me on this?
Depends on the contents of the file you want to read and output in the list you want to get.
# assuming you have values each on separate line
values = []
for line in open('path-to-the-file'):
values.append(line)
# might want to implement stripping newlines and such in here
# by using line.strip() or .rstrip()
# or perhaps more than one value in a line, with some separator
values = []
for line in open('path-to-the-file'):
# e.g. ':' as a separator
separator = ':'
line = line.split(separator)
for value in line:
values.append(value)
# or all in one line with separators
values = open('path-to-the-file').read().split(separator)
# might want to use .strip() on this one too, before split method
It could be more accurate if we knew the input and output requirements.
Two steps here:
open the file
read the lines
This page might help you: http://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects

Formatting the output of a key from a dictionary

I have a dictionary which store a string as the key, and an integer as the value. In my output I would like to have the key displayed as a string without parenthesis or commas. How would I do this?
for f_name,f_loc in dict_func.items():
print ('Function names:\n\n\t{0} -- {1} lines of code\n'.format(f_name, f_loc))
output:
Enter the file name: test.txt
line = 'def count_loc(infile):'
There were 19 lines of code in "test.txt"
Function names:
('count_loc(infile)',) -- 15 lines of code
Just incase it wasn't clear, I would like the last line of the output to be displayed as:
count_loc(infile) -- 15 lines of code
EDIT
name = re.search(func_pattern, line).groups()
name = str(name)
Using type() before my output, I verified it remains a string, but the output is as it was when name was a tuple
I don't have Python 3 so I can't test this, but the output of f_name makes it look like it is a tuple with one element in it. So you would change .format(f_name, f_loc) to .format(f_name[0], f_loc)
EDIT:
In response to your edit, try using .group() instead of .groups()
To elaborate on Peter's answer, It looks to me like you're assigning a one-item tuple as the key of your dictionary. If you're evaluating an expression in parentheses somewhere and using that as the key, be sure you don't have a stray comma in there.
Looking at your further edited answer, it's indeed because you're using the groups() method of your regex match. That returns a tuple of (the entire matched section + all the matched groups), and since you have no groups, you want the entire thing. group() with no parameters will give you that.
I expect you have a problem with your parsing code. The lines as written should work as expected.
Since the key is some type of tuple, you may want to join the different elements before printing. We can't really tell what the significance of the key is from the snippet shown.
So you could do something like such:
.format(", ".join(f_name), f_loc)

Categories

Resources