I'm working on a code that sends mails to the persons given in the text file.
This is the text file:
X,y#gmail.com
Z,v#gmail.com
This is my code:
with open("mail_list.txt","r",encoding ="utf-8") as file:
a = file.read()
b = a.split("\n")
d = []
for i in b:
c = i.split(",")
d.append(c)
for x in d:
for y in x:
print(x[0])
print(x[1])
The output should be:
X
y#gmail.com
Z
v#gmail.com
But instead it is:
X
y#gmail.com
X
y#gmail.com
Z
v#gmail.com
Z
v#gmail.com
Why is that?
How can I fix it?
You're iterating over the columns in every row, but not using the column value:
for x in d:
for y in x:
print(y)
Please have a look on this solution. I believe this is more elegant and efficient than the current one. Don't just rely on line break splitting. Instead get all the data in form of lines already split by \n(line break) and then use the content as per your requirements.
lines = []
with open('mail_list.txt') as f:
lines = f.readlines()
for line in lines:
info = line.split(',')
print(info[0])
print(info[1])
You need to only iterate on list d.
with open("mail_list.txt", "r", encoding ="utf-8") as file:
a = file.read()
b = a.split("\n")
d = []
for i in b:
c = i.split(",")
d.append(c)
for x in d:
print(x[0])
print(x[1])
To make it simpler, you can read your file line by line and process it at the same time. The strip() method removes any leading (spaces at the beginning) and trailing (spaces or EOL at the end) characters.
with open("mail_list.txt", "r", encoding ="utf-8") as file:
for line in file:
line_s = line.split(",")
print(line_s[0])
print(line_s[1].strip())
Related
I am learning Python and making a program with product() in it. I have an input .txt file with lines. It takes banlist, which can contain same line as in input .txt file.
I need to delete some lines that contain specific keyword. I have tried using seek() to write only lines that i need, but i keep getting unusual results that can be repeated lines, deleting not working.
from itertools import product
with open('banLeftSide.txt') as f:
c = f.read().splitlines()
with open('banRightSide.txt') as f:
d = f.read().splitlines()
with open('input.txt') as f:
a = f.read().splitlines()
with open('input.txt') as f:
b = f.read().splitlines()
if c != []:
for i,thing in enumerate(a):
if thing in c:
a[i] = 'keyword'
if d != []:
for i,thing in enumerate(b):
if thing in d:
b[i] = 'keyword'
temp = product(a, b)
for i in list(temp):
li = list(i)
with open('output.txt', 'w') as f:
for i in product(a, b):
if i[0] != i[1]:
f.write(" - ".join(i) + '\n')
with open('output.txt', 'r'+) as txt_file:
temp = txt_file.readlines()
txt_file.seek(0)
for line in temp:
if not 'keyword' in line:
txt_file.write(line)
Examples of input.txt:
a
b
c
d
Examples of banLeftSide.txt or banRightSide.txt:
c
I have made a code in python that read text file (Test.text), the text file contains data like in below
10 20
15 90
22 89
12 33
I can read specific line by use this code
particular_line = linecache.getline('Test.txt', 1)
print(particular_line)
I tried to use code to split the text file to x, y value but it got all lines not the specific line that I need
with open('Test.txt') as f:
x,y = [], []
for l in f:
row = l.split()
x.append(row[0])
y.append(row[1])
So how to get specific line and split it to two values x and y
You might do
particular_line = linecache.getline('Test.txt', 1)
print(particular_line)
x, y = particular_line.split()
print(x) # 10
print(y) # 20
.split() does give list with 2 elements, I used so called unpacking to get 1st element into variable x and 2nd into y.
You are missing the readlines in your code
with open('Test.txt') as f:
x,y = [], []
for l in f.readlines():
row = l.split()
x.append(row[0])
y.append(row[1])
import pandas as pd
xy = pd.read_csv("Test.txt", sep=" ", header=None).rename(columns={0:"x", 1:"y"})
Now you can access to all x and y values with xy.x.values and xy.y.values.
Note that I chose sep=" " as separator becose I suppose that your x and y are separated by a single space in you file.
This is a rather condensed example:
with open("input.txt", "r") as f:
data = f.read()
# Puts data into array line by line, then word by word
words = [y.split() for y in data.split("\n")]
# Gets first word (x)
x = [x[0] for x in words]
# Gets second word (y)
y = [x[1] for x in words]
Where [y.split() for y in data.split("\n")] gets each line by splitting at \n and splits the x and y values (.split()) by the space in-between them
To get the specific line you can use this code
with open('Test.txt') as f:
particular_line = f.readlines()[1]
print(particular_line)
Notice the index inside [], it starts from 0 as same as most other languages. For example, if you want to get the first line, you'd change it to 0.
By parsing it into two variables you can use
x, y = particular_line.split()
print(x)
print(y)
So, put them together,
with open('Test.txt') as f:
particular_line = f.readlines()[1]
print(particular_line)
x, y = particular_line.split()
print(x)
print(y)
You might also need it in a function format,
def get_particular_line_to_x_y(filename, line_number):
with open(filename) as f:
particular_line = f.readlines()[line_number]
return particular_line.split()
if __name__ == '__main__':
x, y = get_particular_line_to_x_y('Test.txt', 0)
print(x)
print(y)
My text file looks like so: comp_339,9.93/10
I want to extract just rating point as a float value. I couldn't solve this with 'if' statement.
Is there any simple solution for this?
d2 = {}
with open('ra.txt', 'r') as r:
for line in r:
s = line.strip().split(',')
d2[s[0]] = "".join(s[1:])
print(d2)
You can do it like this:
with open('ra.txt', 'r') as r:
for line in r:
s = line.strip().split(',')
rating, _ = s[1].split("/", 1)
print(rating)
First you split the line string into "comp399" and "9.93/10"
then you keep the latter and split it again with "/" and keep the first part and convert to float.
line = "comp_339,9.93/10"
s = float(line.split()[1].split('/')[0])
# output: 9.93
You may use a simple regular expression:
import re
line = "comp_339,9.93/10"
before, rating, highscore = re.split(r'[/,]+', line)
print(rating)
Which yields
9.93
You should try this code
ratings={}
with open('ra.txt' , 'r') as f:
for l in f.readlines():
if len(l):
c, r= ratings.split(',')
ratings[c.strip()]=float(r.strip().split('/')[0].strip())
I have a file which contains lines of the form
2.484 5.234
6.123 1.461
1.400 9.381
I would like to read these into python lists x containing the first value of each line and y containing the second value of each line.
How can I achieve this? Here is my attempt:
x = []
y = []
with open(filename) as file_:
for line in file_:
a, b = line
x.append(a)
y.append(b)
a, b = line
cannot work because you're trying to unpack a string into 2 elements (unless the string itself is 2 elements long, which isn't the case)
you want to convert to float & unpack the splitted line like this:
a, b = map(float,line.split())
in that case split() without arguments takes care of multiple spaces, linefeeds, tabs... like awk would do so it's pretty easy.
You can try this:
data =[map(float, i.strip('\n').split()) for i in open('filename.txt')]
You can do that
x = []
y = []
with open("file.txt", "r") as ins:
for line in ins:
elt = line.split()
x.append(elt[0])
y.append(elt[1])
print x
print y
I have a text file with numbers stored in the following format:
1.2378 4.5645
6.789 9.01234
123.43434 -121.0212
... and so on.
I wish to read these values into two arrays, one for x co-ordinates and the other for y co-ordinates. Like, so
x[0] = 1.2378
y[0] = 4.5645
x[1] = 6.789
y[1] = 9.01234
... and so on.
How should I go about reading the text file and storing values?
One method:
x,y = [], []
for l in f:
row = l.split()
x.append(row[0])
y.append(row[1])
where f is the file object (from open() for instance)
You could also use the csv library
import csv
with open('filename','r') as f:
reader = csv.reader(f,delimeter=' ')
for row in reader:
x.append(row[0])
y.append(row[1])
And you can also use zip to make it more succinct (though possibly less readable:
x,y = zip(*[l.split() for l in f])
where f is the file object, or
import csv
x,y = zip(*csv.reader(f,delimeter=' '))
again where f is the file object. Not that the last two methods will load the entire file into memory (although if you are using python 3 you can use generator expressions and avoid that).
Read it per lines, and split it using split:
with open('f.txt') as f:
for line in f:
x, y = line.split()
#do something meaningful with x and y
Or if you don't mind with storing the whole list to your computer's memory:
with open('f.txt') as f:
coordinates = [(c for c in line.split()) for line in f]
And if you want to store the xs and ys in separate variables:
xes = []
ys = []
with open('f.txt') as f:
for line in f:
x, y = line.split()
xes.append(x)
ys.append(y)