Display all data in vertical format python csv - python

Hello guys i tried a lot of method displaying the below code. I wanted it to be displayed in another orientation.
This Code display the following excel file.
newDirRH = "C:/Plots"
newfile = newDirRH + "/TabulatedStatsVSM.csv"
with open(newfile, "wb") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["NameIP", "TypeIP", "FieldIP", "SignalIP", "NameOP", "TypeOP", "FieldOP", "SignalOP"])
writer.writerow(["name","type","[cm]","[m]","name","type","[cm]","[m]"])
for field, signal, field1, signal1 in zip(FieldIP, signalIP, FieldOP, signalOP):
writer.writerow([NameIP, TypeIP,field, signal, NameOP, TypeOP,field1, signal1])
NameIP = TypeIP = NameOP = TypeOP = ''
Excel file displayed by the following code.
I am trying to achieve something like this. Is it possible??
This excel file, i edited myself.

Your problem: There is no "\n" in writer.writerow thats is why you keep having error found. For csv you have to write a row at a time. The following code is what you want.
import csv
FieldIP = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
FieldOP = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
signalIP = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,0.10,0.11,0.12,0.13,0.14,0.15,0.16,0.17,0.18,0.19,0.20]
signalOP = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,0.10,0.11,0.12,0.13,0.14,0.15,0.16,0.17,0.18,0.19,0.20]
NameIP = "JDP123"
TypeIP = "ID123"
NameOP = "JDP124"
TypeOP = "ID124"
newDirRH = "C:/VSMPlots"
newfile = newDirRH + "/TabulatedStatsVSM1.csv"
with open(newfile, "wb") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["NameIP", "TypeIP", "NameOP", "TypeOP"])
writer.writerow([NameIP, TypeIP, NameOP, TypeOP])
writer.writerow([" "])
writer.writerow(["FieldIP", "SignalIP", "FieldOP", "SignalOP"])
for field, signal, field1, signal1 in zip(FieldIP, signalIP, FieldOP, signalOP):
writer.writerow([field, signal, field1,signal1])
print "Done"

write in writerow 1 at a time and you should be fine.
writer.writerow(["NameIP", "TypeIP", "NameOP", "TypeOP"])
writer.writerow([NameIP, TypeIP, NameOP, TypeOP])
writer.writerow([" "]) # Leaving a space accordng to your excel
writer.writerow(["FieldIP", "SignalIP", "FieldOP", "SignalOP"])
for field, signal, field1, signal1 in zip(FieldIP, signalIP, FieldOP, signalOP):
writer.writerow([field, signal, field1,signal1])

Related

Write multiple rows to a CSV

I have a small GUI which should write the values ​​into a CSV file. However, the header is always written instead of just the new entries.
this is how it looks in the csv:
Amount, Time
1000,12:13:40
Amount, Time
2000,12:14:30
What I want:
Amount, Time
1000,12:13:40
2000,12:14:30
def submit():
import csv
import datetime
with open("Data_amount.csv", "a", newline="") as csvfile:
writer = csv.writer(csvfile)
#Header
writer.writerow(["Amount", "Time"])
#Input
input_amount = entry_listbox.get()
#Time
now = datetime.datetime.now()
now_str = now.time().strftime("%H:%M:%S")
writer.writerow([input_amount, now_str])
timestamp = datetime.datetime.now()
input_amount2 = entry_listbox.get()
if input_amount2 != "":
listbox_stuekzahlen.insert(tkinter.END, f'{timestamp:%H:%M:%S} - {input_amount2} Stk.')
entry_listbox.delete(0,tkinter.END)
else:
tkinter.messagebox.showwarning(title="Warning!", message="INPUT!")
You unconditionally write the header again each time you call submit. Either:
Remove that header write, and have, somewhere outside submit (early in your program, run exactly once), the code that initializes (opens in "w" mode so the file is cleared) the file with just the header, so each submit doesn't add an extra copy, or
Leave the header write in, but make it conditional on the file being empty (so you only write it when the file is already empty, and otherwise assume the file already has the header), e.g.
with open("Data_amount.csv", "a", newline="") as csvfile:
writer = csv.writer(csvfile)
#Header
if not os.fstat(csvfile.fileno()).st_size:
writer.writerow(["Amount", "Time"]) # Write header only if input is empty

How to read a CSV and adapt + write every row to another CSV?

I tried this but it just writes "lagerungskissen kleinkind,44" several times instead of transferring every row.
keyword = []
rank = []
rank = list(map(int, rank))
data = []
with open("keywords.csv", "r") as file:
for line in file:
data = line.strip().replace('"', '').split(",")
keyword = data[0]
rank = data[3]
import csv
with open("mynew.csv", "w", newline="") as f:
thewriter = csv.writer(f)
thewriter.writerow(["Keyword", "Rank"])
for row in keyword:
thewriter.writerow([keyword, rank])
It should look like this
This is writing the same line in your output CSV because the final block is
for row in keyword:
thewriter.writerow([keyword, rank])
Note that the keyword variable doesn't change in the loop, but the row does. You're writing that same [keyword, rank] line len(keyword) times.
I would use the csv package to do the reading and the writing for this. Something like
import csv
input_file = '../keywords.csv'
output_file = '../mynew.csv'
# open the files
fIn = open(input_file, 'r', newline='')
fOut = open(output_file, 'w')
csvIn = csv.reader(fIn, quotechar='"') # check the keyword args in the docs!
csvOut = csv.writer(fOut)
# write a header, then write each row one at a time
csvOut.writerow(['Keyword', 'Rank'])
for row in csvIn:
keyword = row[0]
rank = row[3]
csvOut.writerow([keyword, rank])
# and close the files
fOut.close()
fIn.close()
As as side note, you could write the above using the with context manager (e.g. with open(...) as file:). The answer here shows how to do it with multiple files (in this case fIn and fOut).

How to export text to a new file, userinput?

So i wrote a little program in python which allows me to take a .csv file, filter out the lines i need and then export these into a new .txt file.
This worked quite well, so i decided to make it more user friendly by allowing the user to select the file that should be converted by himself through the console (command line).
My problem: The file is imported as a .csv file but not exported as a .txt file which leads to my program overwriting the original file which will be emptied because of a step in my program which allows me to delete the first two lines of the output text.
Does anyone know a solution for this?
Thanks :)
import csv
import sys
userinput = raw_input('List:')
saveFile = open(userinput, 'w')
with open(userinput, 'r') as file:
reader = csv.reader(file)
count = 0
for row in reader:
print(row[2])
saveFile.write(row[2] + ' ""\n')
saveFile.close()
saveFile = open(userinput, 'r')
data_list = saveFile.readlines()
saveFile.close()
del data_list[1:2]
saveFile = open(userinput, 'w')
saveFile.writelines(data_list)
saveFile.close()
Try This:
userinput = raw_input('List:')
f_extns = userinput.split(".")
saveFile = open(f_extns[0]+'.txt', 'w')
I think you probably just want to save the file with a new name, this Extracting extension from filename in Python talks about splitting out the extension so then you can just add your own extension
you would end up with something like
name, ext = os.path.splitext(userinput)
saveFile = open(name + '.txt', 'w')
You probably just need to change the extension of the output file. Here is a solution that sets the output file extension to .txt; if the input file is also .txt then there will be a problem, but for all other extensions of the input file this should work.
import csv
import os
file_name = input('Name of file:')
# https://docs.python.org/3/library/os.path.html#os.path.splitext
# https://stackoverflow.com/questions/541390/extracting-extension-from-filename-in-python
file_name, file_ext_r = os.path.splitext(file_name)
file_ext_w = '.txt'
file_name_r = ''.format(file_name, file_ext_r)
file_name_w = ''.format(file_name, file_ext_w)
print('File to read:', file_name_r)
print('File to write:', file_name_w)
with open(file_name_r, 'r') as fr, open(file_name_w, 'w') as fw:
reader = csv.reader(fr)
for i, row in enumerate(reader):
print(row[2])
if i >= 2:
fw.write(row[2] + ' ""\n')
I also simplified your logic to avoid writting the first 2 lines to the output file; no need to read and write the output file again.
Does this work for you?

Python CSV parsing and file generation

I've got a CSV of over 500 entries and I'm trying to generate redirect files. The formatting of the CSV is:
/contact,/contact-us,
/about,/about-us,
The /contact is the old URL and the /contact-us is the new URL.
The formatting of the desired .htm file is:
url = "/contact"
is_hidden = 0
==
<?php
function onStart(){return Redirect::to("/contact-us");}
?>
==
The filename for the .htm files are unimportant (could be 1.htm, 2.htm, etc.).
I haven't really touched Python in several years and I'm not sure if it's the best option, but from what I've been reading, it seems like it's a solid choice for CSV parsing.
Any help would be greatly appreciated.
Edit:
This is what I have so far
import pip
import csv
with open('redirects.csv') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
print 'url = "'+row[0]+'\nis_hidden = 0\n==\n\n<?php\nfunction onStart(){return Redirect::to("'+row[1]+'");}\n?>\n=='
This prints out exactly what I need. I just need to put each entry into a .htm file (auto-incremented filename).
Edit #2:
I got what I was looking for with this code:
import pip
import csv
count = 0
with open('redirects.csv') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
count += 1
count_str = str(count)
file = open('redirects/'+count_str+'.htm', 'w')
file.write('url = "' + row[0] + '"\nis_hidden = 0\n==\n\n<?php\nfunction onStart(){return Redirect::to("' + row[1] + '");}\n?>\n==')
file.close()
If I understand correctly, something like below might work.
directories = open('filename', 'r').read()
splitted = directories.split(",")
correctlyformatted = [x.strip() for x in splitted]
counter = 0
for i in correctlyformatted:
f=open(str(counter) + '.html', 'w')
f.writeLines([
'url = "' + i + '"',
'i.s_hidden = 0',
'==',
'<?php',
'function onStart(){return Redirect::to("' + i +'");}',
'?>', '=='])
counter += 1

How to save multiple xml files in python

I'm attempting to get a series of weather reports from a website, I have the below code which creates the needed URLs for the XMLs I want, what would be the best way to save the returned XMLs with different names?
with open('file.csv') as csvfile:
towns_csv = csv.reader(csvfile, dialect='excel')
for rows in towns_csv:
x = float(rows[2])
y = float(rows[1])
url = ("http://api.met.no/weatherapi/locationforecast/1.9/?")
lat = "lat="+format(y)
lon = "lon="+format(x)
text = url + format(lat) + ";" + format(lon)
I have been saving single XMls with this code;
response = requests.get(text)
xml_text=response.text
winds= bs4.BeautifulSoup(xml_text, "xml")
f = open('test.xml', "w")
f.write(winds.prettify())
f.close()
The first column of the CSV file has city names on it, I would ideally like to use those names to save each XML file as it is created. I'm sure another for loop would do, I'm just not sure how to create it.
Any help would be great, thanks again stack.
You have done most of the work already. Just use rows[0] as your filename. Assuming rows[0] is 'mumbai', then rows[0]+'.xml' will give you 'mumbai.xml' as the filename. You might want to check if city names have spaces which need to be removed, etc.
with open('file.csv') as csvfile:
towns_csv = csv.reader(csvfile, dialect='excel')
for rows in towns_csv:
x = float(rows[2])
y = float(rows[1])
url = ("http://api.met.no/weatherapi/locationforecast/1.9/?")
lat = "lat="+format(y)
lon = "lon="+format(x)
text = url + format(lat) + ";" + format(lon)
response = requests.get(text)
xml_text=response.text
winds= bs4.BeautifulSoup(xml_text, "xml")
f = open(rows[0]+'.xml', "w")
f.write(winds.prettify())
f.close()

Categories