how to iterate lines from a text file and do something? - python

with open("list.txt") as f:
lst = (f)
print(lst)
for h in lst:
print(lst[h])
In a loop i want to open a file take 1st line as a var and do something with selenium and then take another line and do the selenium stuff again until last line.
trying since evening only getting errors. like list indices must be integers or slices, not str.

Why not this :
with open("list.txt") as f:
for line in f:
print(line)
# do selenium stuff
if somecondition :
break

with open("list.txt", 'r') as f:
lines = f.readlines()
for line in Lines:
# do smth here

Looks like you want to read the data in the file list.txt and want to print out the list with each line of file list.txt as an element of lst. You would want to do that like-
lst = []
with open("list.txt") as f:
for new in f:
if new != '\n':
addIt = new[:-1].split(',')
lst.append(addIt)
for h in lst:
print(lst[h])

You can try something like this as well
lst = open("list.txt").read().split('\n')
for each in lst:
print(each)

Related

How to extract the first and last value from a txt file, in python?

I have a txt file made like this:
2,5,25,6
3,5,78,6,
5,23,24,85
6,4,79,9
69,23,12,51
I should extract only two values that are the first value in the first line 2 and the first value in the last line 69.
The program I wrote is the following:
with open("C:\values.txt", "r") as fp:
lines = fp.readlines()
for i in range(0, len(lines)):
print(lines[i])
but I can only print all the lines present in the txt file.
After opening the file via iostream, you can use readlines() to transfer the whole data to the list. And you can get the value you want with the index of the list.
with open("value.txt", "r") as fp:
lines = fp.readlines()
first = lines[0].split(',')[0]
end = lines[-1].split(',')[0]
print(first, end)
Use indexing along with .read():
with open(r"C:\values.txt", "r") as fp:
txt = fp.read().strip()
first_val = int(txt.split("\n")[0].split(",")[0])
last_val = int(txt.split("\n")[-1].split(",")[0])
something like the below
with open("values.txt", "r") as fp:
lines = [l.strip() for l in fp.readlines()]
first_and_last = [lines[0], lines[-1]]
for l in first_and_last:
print(l.split(',')[0])
output
2
69

Extracting data from a .txt file

I have this data in my sample.txt file:
A2B3,32:45:63
A4N6,17:72:35
S2R3,13:14:99
What I want to do is to put those data in an array but I'm having problems separating those with commas.
My code goes like this:
with open('sample.txt', 'r') as f:
for line in f:
x = f.read().splitlines()
print(x)
And the output goes like this:
['A2B3,32:45:63','A4N6,17:72:35','S2R3,13:14:99']
I altered my code in different ways to separate those two variables with commas but I can't seem to make it work. Can someone help me achieve this output?
['A2B3','32:45:63','A4N6','17:72:35','S2R3','13:14:99']
use line.split(',') to seperate the line at the ",".
x = []
with open('sample.txt', 'r') as f:
for line in f:
for j in line.split(','):
x.append(j.split('\n')[0])
print(x)
Use this code, which splits the lines into a list like you have, and then splits those items at the comma.
filename = "sample.txt"
with open(filename) as file:
lines = file.read().split("\n")
output = []
for l in lines:
for j in l.split(","):
output.append(j)
print(output)
Output:
['A2B3', '32:45:63', 'A4N6', '17:72:35', 'S2R3', '13:14:99']
You probably could just do:
data = list()
with open('sample.txt', 'r') as f:
for line in f.readlines():
data.append(line)
And you should end up with list of appended lines. It's also faster on big files than just .splitlines() since .readlines() is implemented in C and doesn't load whole file in memory.
yes, it's very simple...
after separate all line, you get list look like
['A2B3,32:45:63','A4N6,17:72:35','S2R3,13:14:99']
then after again you separate that each element by comma(,) and add it into new list like
list_a = ['A2B3,32:45:63','A4N6,17:72:35','S2R3,13:14:99']
final_list = []
for i in list_a:
part_1, part_2 = i.split(',')
final_list.append(part_1)
final_list.append(part_2)
print(final_list)
And it will give your desire output like
['A2B3','32:45:63','A4N6','17:72:35','S2R3','13:14:99']
it is not a redundant way but for you very easy to understand
Thank You :)
Here you go, just iterating once over the lines:
res = []
with open('sample.txt', 'r') as f:
for line in f:
res += line.strip().split(",")
print(res)
Gives:
['A2B3', '32:45:63', 'A4N6', '17:72:35', 'S2R3', '13:14:99']
Though I wonder why you'd want to have everything in a list, I think you are missing the link between the items, maybe could be more useful to keep them in tuples like this:
res = []
with open('sample.txt', 'r') as f:
for line in f:
res.append(tuple(line.strip().split(",")))
print(res)
Gives:
[('A2B3', '32:45:63'), ('A4N6', '17:72:35'), ('S2R3', '13:14:99')]
FMPOV this result is better to go along. But nevermind, I guess, you'll find your solution from one of those poseted here.
x = [i.replace("\n","").split(',')for i in open('data.txt', 'r')]
print(x)
print(x[0][1])

File manipulation: lists, removing `\n`s

Code:
with open ("Test1_Votes.txt", 'r'):
f = open("Test1_Votes.txt")
lines = f.readlines()
print(lines[0])
print(lines[1])
all_lines = []
lines = lines.rstrip("\n") #does not work
for line in lines:
#in here
all_lines.append(line)
print(all_lines)
Right now it prints outputs something like:
['1,2,3,0,0\n', ...]
I would like it to output [[1, 2, 3, 0, 0], ...]
File Sample:
1,2,3,0,0
1,3,2,0,0
2,3,1,0,0
3,0,1,2,0
3,0,1,0,2
The zero's must be kept in there and there is not a blank line in between each line in the .txt
Any suggestions/answers?
Thanks in advance
You have a few minor glitches in your code. The with context opens the file, so you don't need the second open statement. lines is a list of each line in your file, including the trailing '\n' characters, to remove them you can iterate over the lines list and strip off the new line characters.
with open("Test1_Votes.txt", 'r') as f:
lines = [line.rstrip() for line in f.readlines()]
print(lines[0])
print(lines[1])
You're currently stripping the new line character only from the last line of the file, if any. You should strip from each line instead:
with open ("Test1_Votes.txt") as f:
all_lines = []
for line in f:
line = line.rstrip("\n") # strip new line character
lst = [int(x) for x in line.split(',')] # split line and cast to int
all_lines.append(lst)
Of course, you can put the entire logic into a list comprehension:
with open ("Test1_Votes.txt") as f:
all_lines = [[int(x) for x in l.rstrip("\n").split(',')] for l in f]
try this
fle=open("infile.txt", "r")
lst=fle.readlines()
lst=[i.strip() for i in lst]
for i in lst:
print i
print lst
Use re.split() instead of readlines():
import re
your_file='abc def\nghi jkl\nmno pqr...'
all_lines=re.split('\n', your_file)
A one liner might look like this:
all_lines = list([int(x) for x in line.replace('\n', '').split(',')] for line in open ("filepath", 'r').readlines())
print(all_lines)

Breaking txt file into list of lists by character and by row

I am just learning to code and am trying to take an input txt file and break into a list (by row) where each row's characters are elements of that list. For example if the file is:
abcde
fghij
klmno
I would like to create
[['a','b','c','d','e'], ['f','g','h','i','j'],['k','l','m','n','o']]
I have tried this, but the results aren't what I am looking for.
file = open('alpha.txt', 'r')
lst = []
for line in file:
lst.append(line.rstrip().split(','))
print(lst)
[['abcde', 'fghij', 'klmno']]
I also tried this, which is closer, but I don't know how to combine the two codes:
file = open('alpha.txt', 'r')
lst = []
for line in file:
for c in line:
lst.append(c)
print(lst)
['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o']
I tried to add the rstrip into the lst.append but it didn't work (or I didn't do it properly). Sorry - complete newbie here!
I should mention that I don't want newline characters included. Any help is much appreciated!
This is very simple. You have to use the list() constructor to make a string into its respective characters.
with open('alpha.txt', 'r') as file:
print([list(line)[:-1] for line in file.readlines()])
(The with open construct is just an idiom, so you don't have to do all the handling with the file like closing it, which you forgot to do)
If you want to split a string to it's charts you can just use list(s) (where s = 'asdf'):
file = open('alpha.txt', 'r')
lst = []
for line in file:
lst.append(list(line.strip()))
print(lst)
You are appending each entry to your original list. You want to create a new list for each line in your input, append to that list, and then append that list to your master list. For example,
file = open('alpha.txt', 'r')
lst = []
for line in file:
newLst = []
for c in line:
newLst.append(c)
lst.append(newLst)
print(lst)
use a nested list comprehension. The outer loop iterates over the lines in the file and the inner loop over the characters in the strings of each line.
with open('alpha.txt') as f:
out = [[char for char in line.strip()] for line in f]
req = [['a','b','c','d','e'], ['f','g','h','i','j'],['k','l','m','n','o']]
print(out == req)
prints
True

Python, add items from txt file into a list

Say I have an empty list myNames = []
How can I open a file with names on each line and read in each name into the list?
like:
> names.txt
> dave
> jeff
> ted
> myNames = [dave,jeff,ted]
Read the documentation:
with open('names.txt', 'r') as f:
myNames = f.readlines()
The others already provided answers how to get rid of the newline character.
Update:
Fred Larson provides a nice solution in his comment:
with open('names.txt', 'r') as f:
myNames = [line.strip() for line in f]
f = open('file.txt','r')
for line in f:
myNames.append(line.strip()) # We don't want newlines in our list, do we?
names=[line.strip() for line in open('names.txt')]
#function call
read_names(names.txt)
#function def
def read_names(filename):
with open(filename, 'r') as fileopen:
name_list = [line.strip() for line in fileopen]
print (name_list)
This should be a good case for map and lambda
with open ('names.txt','r') as f :
Names = map (lambda x : x.strip(),f_in.readlines())
I stand corrected (or at least improved). List comprehensions is even more elegant
with open ('names.txt','r') as f :
Names = [name.rstrip() for name in f]
The pythonic way to read a file and put every lines in a list:
from __future__ import with_statement #for python 2.5
Names = []
with open('C:/path/txtfile.txt', 'r') as f:
lines = f.readlines()
Names.append(lines.strip())
Names = []
for line in open('names.txt','r').readlines():
Names.append(line.strip())
strip() cut spaces in before and after string...

Categories

Resources