How to print names from a text file in Python - python-3.x

I have got a text document that looks something like this
Kei 1 2 3 4 5
Igor 5 6 7 8 9
Guillem 8 7 6 9 5
How can I print their names and their last 3 scores
I came up with this
class_3 = open('class_3','r')
read = class_3.read()
read.split()
print(read)
But it came out with just
K
Please help

You can loop over file object and split the lines, then use a simple indexing to print the expected output:
with open('example.txt') as f:
for line in f:
items = line.split()
print items[0], ' '.join(items[-3:])
Output :
Kei 3 4 5
Igor 7 8 9
Guillem 6 9 5
The benefit of using with statement for opening the file is that it will close the file at the end of the block automatically.
As a more elegant approach you can also use unpacking assignment in python 3.X:
with open('example.txt') as f:
for line in f:
name, *rest = line.split()
print(name, ' '.join(rest))

In python 3.x you will have to change #Kasramvd's answer slightly. You have to add parenthesis around the parameters of the call to the print function.
with open('example.txt') as f:
for line in f:
items = line.split()
print(items[0], ' '.join(items[-3:]))

Related

How to skip N central lines when reading file?

I have an input file.txt like this:
3
2
A
4
7
B
1
9
5
2
0
I'm trying to read the file and
when A is found, print the line that is 2 lines below
when B is found, print the line that is 4 lines below
My current code and current output are like below:
with open('file.txt') as f:
for line in f:
if 'A' in line: ### Skip 2 lines!
f.readline() ### Skipping one line
line = f.readline() ### Locate on the line I want
print(line)
if 'B' in line: ## Skip 4 lines
f.readline() ### Skipping one line
f.readline() ### Skipping two lines
f.readline() ### Skipping three lines
line = f.readline() ### Locate on the line I want
print(line)
'4\n'
7
'1\n'
'9\n'
'5\n'
2
>>>
Is printing the values I want, but is printing also 4\n,1\n... and besides that, I need to write several f.realines()which is not practical.
Is there a better way to do this?
My expected output is like this:
7
2
Here is a much simpler code for you:
lines=open("file.txt","r").read().splitlines()
#print(str(lines))
for i in range(len(lines)):
if 'A' in lines[i]:
print(lines[I+2]) # show 2 lines down
elif 'B' in lines[i]:
print(lines[I+4]) # show 4 lines down
This reads the entire file as an array in which each element is one line of the file. Then it just goes through the array and directly changes the index by 2 (for A) and 4 (for B) whenever it finds the line it is looking for.
if you don't like repeated readline then wrap it in a function so the rest of the code is very clean:
def skip_ahead(it, elems):
assert elems >= 1, "can only skip positive integer number of elements"
for i in range(elems):
value = next(it)
return value
with open('file.txt') as f:
for line in f:
if 'A' in line:
line = skip_ahead(f, 2)
print(line)
if 'B' in line:
line = skip_ahead(f, 4)
print(line)
As for the extra output, when the code you have provided is run in a standard python interpreter only the print statements cause output, so there is no extra lines like '1\n', this is a feature of some contexts like the IPython shell when an expression is found in a statement context, in this case f.readline() is alone on it's own line so it is detected as possibly having a value that might be interesting. to suppress this you can frequently just do _ = <expr> to suppress output.

Return statement inside for loop with range not working

I'm trying to work on a problem based on python as:
`Given an integer,print the following values for each integer from 1 to n :
Decimal
Octal
Hexadecimal (capitalized)
Binary`
What I did something like:
def print_format(number):
for i in range(number+1):
decimal=str(i)
binary=str(bin(i))
octa=str(oct(i))
hexagonal=str(hex(i))
return (decimal+' '+octa[2:]+' '+hexagonal[2:].upper()+' '+binary[2:])
print_format(5)
'5 5 5 101'
code returns only last set of value. But, what I'm expecting as,
0 0 0 0
1 1 1 1
2 2 2 10
3 3 3 11
4 4 4 100
5 5 5 101
Part of the code as with print statement works perfectly fine.
def print_format(number):
for i in range(number+1):
decimal=str(i)
binary=str(bin(i))
octa=str(oct(i))
hexagonal=str(hex(i))
print (decimal+' '+octa[2:]+' '+hexagonal[2:].upper()+' '+binary[2:])
Can anyone please explain what I did wrong while using return statement?
In your current attempt, you are looping through your input without doing anything. Return only sees the local variables after the last iteration and returns them. What you want is a generator:
def print_format(number):
for i in range(number+1):
decimal=str(i)
binary=str(bin(i))
octa=str(oct(i))
hexagonal=str(hex(i))
yield (decimal+' '+octa[2:]+' '+hexagonal[2:].upper()+' '+binary[2:])
mygen = print_format(5)
for i in mygen:
print(i)
This should print your desired output.
Just save all strings in a variable spliting with \n and return it.
def print_format(number):
result = ''
for i in range(number+1):
decimal=str(i)
binary=str(bin(i))
octa=str(oct(i))
hexagonal=str(hex(i))
result += decimal+' '+octa[2:]+' '+hexagonal[2:].upper()+' '+binary[2:] + '\n'
return result
print(print_format(5))

How to print of value of i in one line by for loop

I write this code:
for i in range(0,7):
print(i)
so simply the output will be:
1
2
3
4
5
6
But i want to print like this:
1 2 3 4 5 6
how can I print this output like that.??
You can do the following in Python3. If you want more information check out the documentation on the print function here. And you can read about the unpacking operator here.
print(*list(range(0, 7)), sep = " ")
1) make a string first, then print it
" ".join([str(i) for i in range(0, 7)])
2) Duplicate answer How to print with out a new line
You should Google these things first...

Set in python replacing number 10 from a file with 0,1

I have a file with the line:1 2 3 4 5 10. When I add this line to a set in Python, I get {1,2,3,4,5,0} instead of {1,2,3,4,5,10}. How do I code so that I get the 10 inside the set instead of it recognizing it as a 1 and a 0?
EDIT: This was the code I wrote:
states = set()
line = open("filepath", "r").readlines()[0]
states.add(line)
print (states)
Input file content:
1 2 3 4 5 10
As set cannot have a same number twice, the zero which belongs to 10 is being treated as a unique element thus set cannot contain two same elements.
Do something like this to fix it (Assuming you don't have newline characters, if you do, just use the strip method.):
line = open("filepath", "r").readlines()[0]
line = line.split(' ') #Split by Space
number_set = set(line) #Since file is a list after splitting.

start counting how many lines of show command after line 20

Hello I am trying to write a code for counting how many lines after line 20
def line_count(file_name,start=20):
num_lines = 0
with open(file_name,'r') as f:
for line in f:
num_lines += 1
print(num_lines)
An easy way to do this is simply counting the lines in the program and subtracting 20 from it. This is possible in a one-liner:
>>> len(open("file.txt").read().splitlines()) - 20
6
In the above example, this means that the file itself has 26 lines, which is 6 more than 20.

Resources