Get result in one line loop - python

My output:
I have CMShehbaz
CMShehbaz
Expected:
I have CMShehbaz CMShehbaz
I am trying get result in one line. I tried with end="", concat +, but did not
work. I want result in one line.
lines = []
with open('user.txt') as f:
lines = f.readlines()
count = 0
for line in lines:
count += 1
print("I have {} {}".format(line,line) )
print(f'line {count}: {line}')

I'm not quite sure why you have a counter in there if all you want is a single string, but this will do that job.
user.txt
CMShehbaz1
CMShehbaz2
CMShehbaz3
python file
with open('user.txt') as f:
foo = "I have "
bar = " ".join(line.strip() for line in f)
print(foo+bar)
# Or you can do
foo = " ".join(line.strip() for line in f)
print(f"I have {foo}")
Gives you the output:
I have CMShehbaz1 CMShehbaz2 CMShehbaz3
If you want to know how many names are in foo then you can do
print(len(foo.split(' '))) # this will give you 3

I suspect that "user.txt" is a list of usernames each on a new line.
so in your code line will look something like "USER\n"
You can strip off the "\n" character of use some of the solutions posted previously: How to read a file without newlines?

Related

Is there any shortcut in Python to remove all blanks at the end of each line in a file?

I've learned that we can easily remove blank lined in a file or remove blanks for each string line, but how about remove all blanks at the end of each line in a file ?
One way should be processing each line for a file, like:
with open(file) as f:
for line in f:
store line.strip()
Is this the only way to complete the task ?
Possibly the ugliest implementation possible but heres what I just scratched up :0
def strip_str(string):
last_ind = 0
split_string = string.split(' ')
for ind, word in enumerate(split_string):
if word == '\n':
return ''.join([split_string[0]] + [ ' {} '.format(x) for x in split_string[1:last_ind]])
last_ind += 1
Don't know if these count as different ways of accomplishing the task. The first is really just a variation on what you have. The second does the whole file at once, rather than line-by-line.
Map that calls the 'rstrip' method on each line of the file.
import operator
with open(filename) as f:
#basically the same as (line.rstrip() for line in f)
for line in map(operator.methodcaller('rstrip'), f)):
# do something with the line
read the whole file and use re.sub():
import re
with open(filename) as f:
text = f.read()
text = re.sub(r"\s+(?=\n)", "", text)
You just want to remove spaces, another solution would be...
line.replace(" ", "")
Good to remove white spaces.

print last line from the variable output in python

I am looking to get the last line produced from the line variable
bash-4.1$ cat file1_dup.py
#!/usr/bin/python
with open("file1.txt") as f:
lines = f.readlines()
for line in lines:
if "!" in line:
line = line.split()[-1].strip()
print line
output i am getting is as follows ..
-122.1058
-123.1050
-125.10584323
The result i wanted to be printed out is
-125.10584323
Moreover, i got the hint from some goghling and getting the output
desired but that seems bit complicated to me at the point ..
bash-4.1$ cat file2_dup.py
#!/usr/bin/python
def file_read_from_tail(fname,n):
with open(fname) as f:
f=f.read().splitlines()
lines=[x for x in f]
for i in range(len(lines)-n,len(lines)):
line = lines[i].split()[-1]
#line = line.split()[-1]
print line
file_read_from_tail('file1.txt',1)
this yeilds teh desired as folows..
bash-4.1$ ./file2_dup.py
-125.10584323
PS: i just borrow the question for the sake of intrest from:
how to read a specific line and print a specific position in this line using python
You could test if the new line is smaller as the one before like this
#!/usr/bin/python
res_line = 0
with open("file1.txt") as f:
lines = f.readlines()
for line in lines:
if "!" in line:
line = float(line.split()[-1].strip())
if res_line > line:
res_line = line
print res_line
Edit:
you can use enumerate() to get the lines indexed in a loop:
with open("file1.txt", "rt") as f:
lines = f.readlines()
for line, content in enumerate(lines):
# apply your logic to line and/or content here
# by adding ifs to select the lines you want...
print line, content.strip() # do your thing
will output (just to illustrate because I didn't specify any conditions in code above):
0 -122.1058
1 -123.1050
2 -125.10584323
3
or in alternative select your specific line with a condition in a listcomp
by using this code instead:
with open("file1.txt", "rt") as f:
lines = f.readlines()
result = [ content.strip() for line, content in enumerate(lines)
if line == len(lines) - 2] # creates a list with
# only the last line
print result[0]
that will output:
-125.10584323
Try the following:
print [line.split()[-1].strip() for line in lines if '!' in line][-1]
I see a better way by creating an empty list and appending the value comes from the condition and then choose the Index of your choice and list the output , this is good in the sense that it can be used for any line of your intrest which you require to pick.
Lets Suppose i wana the last second line then it can be resuable putting the value in the print section print(lst[-2]) , which will print the last index of second line..
#!/usr/bin/python
file = open('file1.txt', 'r')
lst = list()
for line in file:
if "!" in line:
x= line.split()
lst.append(x[-1])
print(lst[-1])

Return First Letter of Line in File

I am trying to pull the first letter of every line in a file, then print those letters to a new file. I am working step-by-step so I created the code that would be able to pull the first letter of every line, however, when I added the code to read a specific file it appears that it is not properly iterating over the entire files content. Does anyone know why my for loop is not iterating? Or perhaps, is the issue that it is iterating but not properly adding the letters to 'lines'.
def secret2(m):
infile = open(m, 'r')
text = infile.read()
for line in text:
lines = text[0]
for i in range(len(text)):
if text[i] == '\n':
lines += text[i+1]
print(lines)
return(lines)
m.close()
Output:
>>> secret2('file.txt')
A
'A'
>>>
Proper output would be:
>>> secret2('file.txt')
'ALICE'
>>>
Your code is iterating over the characters instead of lines. You could print the first character from each line with following code:
def secret2(m):
with open(m) as infile:
print(''.join(line[0] for line in infile if line))
You want to consider the each line as a single data. So use readlines() instead of read. So your code should be
def secret2(m):
infile = open(m, 'r')
text = infile.readlines()
for j in (text):
print j[0]
You can use this:
def get_1st_chr(your_file, id_line) :
with open(your_file) as f :
text_splitted = f.read().splitlines()
f.close()
return text_splitted[id_line][0]
Or, if you want all of the first lines character:
def get_1st_chr(your_file, nb_lines) :
with open(your_file) as f :
text_splitted = f.read().splitlines()
f.close()
for i in range(nb_lines) :
print(text_splitted[[i][0])
You could replace 0 with the id of the character you want to print of course.

Print full sequence not just first line | Python 3.3 | Print from specific line to end (")

I am attempting to pull out multiple (50-100) sequences from a large .txt file seperated by new lines ('\n'). The sequence is a few lines long but not always the same length so i can't just print lines x-y. The sequences end with " and the next line always starts with the same word so maybe that could be used as a keyword.
I am writing using python 3.3
This is what I have so far:
searchfile = open('filename.txt' , 'r')
cache = []
for line in searchfile:
cache.append(line)
for line in range(len(cache)):
if "keyword1" in cache[line].lower():
print(cache[line+5])
This pulls out the starting line (which is 5 lines below the keyword line always) however it only pulls out this line.
How do I print the whole sequence?
Thankyou for your help.
EDIT 1:
Current output = ABCDCECECCECECE ...
Desired output = ABCBDBEBSOSO ...
ABCBDBDBDBDD ...
continued until " or new line
Edit 2
Text file looks like this:
Name (keyword):
Date
Address1
Address2
Sex
Response"................................"
Y/N
The sequence between the " and " is what I need
TL;DR - How do I print from line + 5 to end when end = keyword
Not sure if I understand your sequence data but if you're searching for each 'keyword' then the next " char then the following should work:
keyword_pos =[]
endseq_pos = []
for line in range(len(cache)):
if 'keyword1' in cache[line].lower():
keyword_pos.append(line)
if '"' in cache[line]:
endseq_pos.append(line)
for key in keyword_pos:
for endseq in endseq_pos:
if endseq > key:
print(cache[key:endseq])
break
This simply compiles a list of all the positions of all the keywords and " characters and then matches the two and prints all the lines in between.
Hope that helps.
I agree with #Michal Frystacky that regex is the way forward. However as I now understand the problem, we need two searches one for the 'keyword' then again 5 lines on, to find the 'sequence'
This should work but may need the regex to be tweaked:
import re
with open('yourfile.txt') as f:
lines = f.readlines()
for i,line in enumerate(lines):
#first search for keyword
key_match = re.search(r'\((keyword)',line)
if key_match:
#if successful search 5 lines on for the string between the quotation marks
seq_match = re.search(r'"([A-Z]*)"',lines[i+5])
if seq_match:
print(key_match.group(1) +' '+ seq_match.group(1))
1This can be done rather simply with regex
import re
lines = 'Name (keyword):','Date','Address1','Address2','Sex','Response"................................" '
for line in lines:
match = re.search('.*?"(:?.*?)"?',line)
if match:
print(match.group(1))
Eventually to use this sample code we would lines = f.readlines() from the dataset. Its important to note that we catch only things between " and another ", if there is no " mark at the end, we will miss this data, but accounting for that isn't too difficult.

how to loop around every word in a line and then every line in a file?

I have a dictonary like
list1={'ab':10,'ba':20,'def':30}.
Now my input file contains :
ab def
ba ab
I have coded:
filename=raw_input("enter file:")
f=open(filename,'r')
ff=open(filename+'_value','w')
for word in f.read().split():
s=0
if word in list1:
ff.write(word+'\t'+list1[word]+'\n');
s+=int(list1[word])
else:
ff.write(word+'\n')
ff.write("\n"+"total:%d"%(s)+"\n")
Now I want my output file to contain:
ab 10
def 30
total: 40
ba 20
ab 10
total: 30
Am not able to loop it for each line. How should I do it? I tried a few variations using f.readlines(), f.read(), and tried looping once, then twice with them. But I cannot get it right.
Instead of giving the answer right away, Let me give you a gist of what you ask:
To read the whole file:
f = open('myfile','r')
data = f.read()
To loop through each line in the file:
for line in data:
To loop through each word in the line:
for word in line.split():
Use it wisely to get what you want.
You need to make 2 loops and not only one:
filename = raw_input("enter file:")
with open(filename, 'r') as f, open(filename + '_value','w') as ff:
# Read each line sequentially
for line in f.read():
# In each line, read each word
total = 0
for word in line.split():
if word in list1:
ff.write("%s\t%s\n" % (word, list1[word]))
total += int(list1[word])
else:
ff.write(word+'\n')
ff.write("\ntotal: %s\n" % total)
I have also cleaned a little bit your code to be more readable. Also see What is the python "with" statement designed for? if you want to understand the with block
with open("in.txt","r") as f:
with open("out.txt","w") as f1:
for line in f:
words = line.split() # split into list of two words
f1.write("{} {}\n".format((words[0]),list1[words[0]])) # write first word plus value
f1.write("{} {}\n".format((words[1]),list1[words[1]])) # second word plus value
f1.write("Total: {}\n".format((int(list1[words[0]]) + int(list1[words[1]])))) # finally add first and second and get total

Categories

Resources