Wrong order of elements when appending to .csv - python

Here is a sample of my current code
for i in pin:
i.click()
time.sleep(4)
f = driver.find_elements_by_xpath('//td[#class="bold"]')
d = driver.find_elements_by_xpath('//td[#class="date"]')
with open("tennisopening.csv","a") as r:
r.write(match + "," + date + "," + score + "\n")
for i in f:
b= i.text
for i in d:
c= i.text
with open("tennisopening.csv","a") as r:
r.write(b + "," + c)
This results in a csv table with cells in the following order:
(b,c,match,date,score,\n)
But, I wish to have it in the following order:
(match,date,score,b,c,\n)
How can I fix this?
Thank you

for i in pin:
i.click()
time.sleep(4)
f = driver.find_elements_by_xpath('//td[#class="bold"]')
d = driver.find_elements_by_xpath('//td[#class="date"]')
with open("tennisopening.csv","a") as r:
for i in f:
b= i.text
for i in d:
c= i.text
with open("tennisopening.csv","a") as r:
r.write(b + "," + c)
r.write(match + "," + date + "," + score + "\n")
This will do
Remember when u write using
with open(filename,mode) as f:
f.write(data)
## data is written only in memory and not yet committed to file.
## data now committed to file
so for the data to be written you must come out of with open() scope
same goes for above data
First come out of this with's scope
with open("tennisopening.csv","a") as r:
r.write(b + "," + c)
and then write into memory
r.write(match + "," + date + "," + score + "\n")
Then come out of parent with scope
;)

Change your inner loop code with this:
with open("tennisopening.csv","a") as r:
for i in f:
b= i.text
for i in d:
c= i.text
r.write("{},{},{},{},{}\n".format(match,date,score,b,c)
This should write "match,date,score,b,c\n" in every line as you asked.
In your code, (match, date, score) will be written only once for every outer loop code.
And you have two instances open for the same file, the instance which writes "b,c" closes first, so it gets written first in the actual file.

Related

Create several multiplication tables instead of one at a time saved to several .txt files

I want to create several multiplication tables by telling this python program how many I want to make. Then, have the program create that number of multiplication tables saved to that same number of created .txt files. I want one table per .txt file. What code do I need to add and how do I do it? Thanks for your time.
This is the program I want to add the functionality to:
def tablep():
n=int(input("Enter a Number:"))
start=int(input("Enter a start:"))
end=int(input("Enter an end:"))
file=open("*table.txt","a")
if start<end:
for i in range(start,end+1):
s = str(n) + "*" + str(i) + "= " + str(n*i)
file.write(s)
file.write("\n")
print(n,"*",i,"=",n*i)
elif start>end:
for i in range(start,end,-1):
s = str(n) + "*" + str(i) + "=" + str(n * i)
file.write(s)
file.write("\n")
print(n, "*", i, "=", n * i)
file.close()
w = tablep()
Example output I want in each file to have. This is just one of the files containing the multiplication table with 3:
3*0= 0
3*1= 3
3*2= 6
3*3= 9
From my understanding of your question, you want each txt file to be unique based on the start and end inputs, so you need to just loop over n times:
def tablep():
n=int(input("Enter a Number:")) # number of txt files
for x in range(0, n):
start=int(input("Enter a start:"))
end=int(input("Enter an end:"))
f_path = "table_" + str(x) + ".txt" # this will numerate each table
file = open(f_path, 'w+') # 'w+' tag will create a file if it doesn't exist
if start<end:
for i in range(start,end+1):
s = str(n) + "*" + str(i) + "= " + str(n*i)
file.write(s)
file.write("\n")
print(n,"*",i,"=",n*i)
elif start>end:
for i in range(start,end,-1):
s = str(n) + "*" + str(i) + "=" + str(n * i)
file.write(s)
file.write("\n")
print(n, "*", i, "=", n * i)
file.close()

Why count doesn't behave normal in python for loop

I have a text file I'm reading from and just threw a counter on there to make sure I grabbed everything but when I implemented a simple counter it acted weird. It works now but I had to do the following:
f = open("street.txt", "r")
l = ""
count = -1
for line in f:
if(line[0].isdigit()):
l = line.replace('\n', '')
else:
count=count+1
l = l + " " + line.replace('\n', '')
c = str(count) + ')'
print(c + l + '\n')
Essentially I was attempting to just run through this file, add every other line to the previous line then number them just as a check with a count variable, that I covered everything. For some reason when the count was running it started at 2 when I had count initially set to 0. It wouldn't print out "1)" until I changed count to -1 initially. That print statement is an L, not a 1. I have no idea why it was doing that. I didn't get an error, it ran fine just with the wrong numbers for about 4-5 runs. And that's an L in the print statement...which should be fairly obvious from the if statement but just in case.
Just initialize count with 0 and increment statement should be in the last.
l = l + " " + line.replace('\n', '')
c = str(count) + ')'
print(c + l + '\n')
count+=1

Trying to modify text file with if statements

I have a text file that I am reading in, and based on certain conditions modifying specific lines and rewriting the file to a new text file. My present code mostly works but one of the elif statements seems to be simply ignored by Python as there are no run time errors. A MWE is as follows:
energy = .1
source = str('source x y z energy=%f' %energy)
c = energy - 0.001
c_string = str("1010 %f %f" %(c, energy))
f = open("file.txt", "r+")
with open ("newfiletxti", 'w') as n:
d = f.readlines()
for line in d:
if not line.startswith("source"):
if not line.startswith("xyz"):
n.write(line)
elif line.startswith("source"):
n.write(source + "\n")
elif line.startswith("xyz"):
n.write(c_string + "\n")
n.truncate()
n.close()
The code:
elif line.startswith("source"):
n.write(source + "\n")
Works as expected where the line in the text file is replaced with the string titled "source" however the next block:
elif line.startswith("xyz"):
n.write(c_string + "\n")
Has no effect. The new text file is simply missing the line that starts with xyz. My guess is my syntax for multiple elif statements is incorrect but I am uncertain as to why.
The first if and elif handle all the cases -- either the line starts with source or it doesn't. I think you need to combine the first if and its nested if into a single condition:
if not line.startswith("source") and not line.startswith("xyz"):
n.write(line)
or the equvivalent (by de Morgan's Laws):
if not(line.startswith("source") or line.startswith("xyz")):
n.write(line)
Or you can make it clearer by reordering your conditions:
if line.startswith("source"):
n.write(source + "\n")
elif line.startswith("xyz"):
n.write(c_string + "\n")
else:
n.write(line)
Try your if block like this:
if line.startswith("source"):
n.write(source + "\n")
elif line.startswith("xyz"):
n.write(c_string + "\n")
else:
n.write(line)
The third elif will never be reached. Here is the code reduced for clarity:
if not line.startswith("source"):
# suff
elif line.startswith("xyz"):
# stuff
Something that starts with "xyz" does not start with "source".

Python error - IndexError: list index out of range

I am learning python so this might sound simple, I am trying to run the code below but I keep getting the error message shown, any thoughts on what could be causing it?
from geopy import geocoders
import csv
g_api_key = 'my_google_api_key'
g = geocoders.GoogleV3(g_api_key)
costco = csv.reader (open('costcolimited.csv'), delimiter = ',')
# Print header
print "Address, City, State, Zip Code, Latitude, Longitude"
for row in costco:
full_addy = row[1]+ "," + row[2]+ "," + row[3] + "," + row[4]
place, (lat,lng) = list (g.geocode(full_addy, exactly_one=FALSE))[0]
full_addy + "," + str(lat) + "," + str(lng)
The error I am getting
Traceback (most recent call last):
File "C:\Python27\geocodelocations.py", line 12, in <module>
full_addy = row[1]+ "," + row[2]+ "," + row[3] + "," + row[4]
IndexError: list index out of range
The error is caused by referring element out of list range. From your code, it is probably because you start counting element from 1. Remember that in python list, index starts from 0. If this is your situation, then shift indexes in
full_addy = row[1]+ "," + row[2]+ "," + row[3] + "," + row[4]
to
full_addy = row[0]+ "," + row[1]+ "," + row[2] + "," + row[3]
Otherwise, check your data structure and make sure it is matched with your code.
Thanks
First of all make sure your CSV file has four columns. Try checking if len(row) >= 4. If it contains you can go on with your code, but the first item in a Python list is referenced by 0 index.
Try something like this:
for row in costco:
if len(row) < 4:
print "Invalid file!"
break
full_addy = row[0]+ "," + row[1]+ "," + row[2] + "," + row[3]
place, (lat,lng) = list (g.geocode(full_addy, exactly_one=FALSE))[0]
full_addy + "," + str(lat) + "," + str(lng)

How to make automated writer to append lines in Python

Here is my Code :
b = 1
a = "line"
f = open("test.txt", "rb+")
if a + " " + str(b) in f.read():
f.write(a + " " + str(b + 1) + "\n")
else:
f.write(a + " " + str(b) + "\n")
f.close()
It prints now line 1 and then line 2, but how can i make this read what is the last "line x" and print out line x + 1?
for example:
test.txt would have
line 1
line 2
line 3
line 4
and my code would append line 5 in the end.
I was thinking maybe some kind of "find last word" kind of code?
How can I do this?
If you know for certain that every line has the format "word number" then you could use:
f = open("test.txt", "rb+")
# Set l to be the last line
for l in f:
pass
# Get the number from the last word in the line
num = int(l.split()[-1]))
f.write("line %d\n"%num)
f.close()
If the format of each line can change and you also need to handle extracting numbers, re might be useful.
import re
f = open("test.txt", "rb+")
# Set l to be the last line
for l in f:
pass
# Get the numbers in the line
numstrings = re.findall('(\d+)', l)
# Handle no numbers
if len(numstrings) == 0:
num = 0
else:
num = int(numstrings[0])
f.write("line %d\n"%num)
f.close()
You can find more efficient ways of getting the last line as mentioned here What is the most efficient way to get first and last line of a text file?

Categories