Python is not saving a csv file, how to fix this? - python-3.x

Here i just tested if it wanted to save in two different ways,
but its not working the file is nowhere to be found on my pc
import csv
def writecsv(data):
with open('CT_10-10-1.csv', 'a') as csvFile:
writer = csv.writer(csvFile)
writer.writerow(data)
csvFile.close()
def write(data):
csvFile = open('CT_10-10-1.csv', 'a')
writer = csv.writer(csvFile)
writer.writerow(data)
#writecsv('10')
write('10')

Related

Strange error when reading a CSV file through method

So, I've got a CSV file (league.csv') in my directory that I want to access through Python.
When I do this:
with open('league.csv', 'r') as csvFile:
csvReader = csv.reader(csvFile)
next(csvReader)
for line in csvReader:
print(line[0])
It works great. But when I try to make it into a function it doesn't work:
def createLeague(csv):
with open(csv, 'r') as csvFile:
csvReader = csv.reader(csvFile)
next(csvReader)
for line in csvReader:
print(line[0])
return
If I call this using:
createLeague('league.csv')
I get the error
csvReader = csv.reader(csvFile)
AttributeError: 'str' object has no attribute 'reader'
This makes no sense because type(csvFile) is not str, and I'm doing exactly the same as above?
Could someone help me, I'm getting really frustrated!
Thanks!
See inline comment what goes wrong.
import csv # "csv" variable at "with open..." overwrites
# cvs module.
from csv import reader # required to use the function "reader" from csv.
def createLeague(csv): # "csv" variable overwrites cvs module.
with open(csv, 'r') as csvFile:
csvReader = reader(csvFile) # skip the csv. here and it works for you.
next(csvReader)
for line in csvReader:
print(line[0])
return
Alternatively:
Below example with changed csv filename does not overwrite the csv module that you just have loaded. The mix-up triggers the error to occur.
import csv
#from csv import reader
def createLeague(csv_file):
with open(csv_file, 'r') as csvFile: # changed variable "csv" filename.
csvReader = csv.reader(csvFile)
next(csvReader)
for line in csvReader:
print(line[0])
return
Don’t use the name of the library as the name of the variable in the function definition.

module 'csv' has no attribute 'writerow'

Trying to write a list to a csv file using:
import csv
with open('filename.csv', 'w', newline='') as csvfile:
wr = csv.writer(csvfile, quoting=csv.QUOTE_ALL)
wr = csv.writerow(list)
returns the error:
module 'csv' has no attribute 'writerow'
Any help is much appreciated.
You have to call writerow() on your writer-instance - not on csv:
Straigth from the documentation:
import csv
with open('eggs.csv', 'w', newline='') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=' ',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

How to convert multiple CSV files in directory to pipe-delimited text files using Python3

So I'm new to Python(3) and need to create a loop that will go through almost 200 CSV files and convert them each into a pipe-delimited .txt file (with the same name).
I have code that does this for 1 file and works perfectly:
import csv
with open('C:/Path/InputFile.csv', 'r') as fin, \
open('C:/Path/OutputFile.txt', 'w') as fout:
reader = csv.DictReader(fin)
writer = csv.DictWriter(fout, reader.fieldnames, delimiter='|')
writer.writeheader()
writer.writerows(reader)
Thanks in advance.
You would modify your code to:
for in_name, out_name in zip(list_of_in_names, list_of_out_names):
with open(in_name, 'r') as fin, open(out_name, 'w') as fout:
...
Where list_of_in_names and list_of_out_names names of files you want to read from and write to respectively.
Edit: To address the issue from the comments you can use the pathlib library:
from pathlib import Path
for in_path in Path('C:/Path').glob('*.csv'):
out_path = in_path.with_suffix('.txt')
with in_path.open('r') as fin, out_path.open('w') as fout:
...

python3 import into csv displaying in every cell

I'm new to python and I'm trying to import some URL's i scraped into a csv file but it is parsing every character in the web addresses into a difference cell. Here's my code:
import csv
with open('test.csv', 'w') as f:
csv_writer = csv.writer(f)
csv_writer.writerow(['Web Address'])
csv_write.writerows(filter_records)
If i put brackets around the filter_records variable, it just returns the entire list of URLs in a single cell
Any guidance would be great.
Thanks
Garrett
You can do something like this:
import csv
filter_records = ['www.google.com', 'www.stackoverflow.com', 'www.facebook.com']
with open('test.csv', 'w') as f:
csv_writer = csv.writer(f)
csv_writer.writerow(['Web Address'])
[csv_writer.writerow([record]) for record in filter_records]
or
import csv
filter_records = ['www.google.com', 'www.stackoverflow.com', 'www.facebook.com']
with open('test.csv', 'w') as f:
csv_writer = csv.writer(f)
csv_writer.writerow(['Web Address'])
csv_writer.writerows([record] for record in filter_records)
This happens because python a string is a list of chars. writerow() method receives a list as param, and writerows() receives a list of lists. So, you will get an comma-split string in every row.

Exporting Python to Excel is only showing one row of data [duplicate]

I have data which is being accessed via http request and is sent back by the server in a comma separated format, I have the following code :
site= 'www.example.com'
hdr = {'User-Agent': 'Mozilla/5.0'}
req = urllib2.Request(site,headers=hdr)
page = urllib2.urlopen(req)
soup = BeautifulSoup(page)
soup = soup.get_text()
text=str(soup)
The content of text is as follows:
april,2,5,7
may,3,5,8
june,4,7,3
july,5,6,9
How can I save this data into a CSV file.
I know I can do something along the lines of the following to iterate line by line:
import StringIO
s = StringIO.StringIO(text)
for line in s:
But i'm unsure how to now properly write each line to CSV
EDIT---> Thanks for the feedback as suggested the solution was rather simple and can be seen below.
Solution:
import StringIO
s = StringIO.StringIO(text)
with open('fileName.csv', 'w') as f:
for line in s:
f.write(line)
General way:
##text=List of strings to be written to file
with open('csvfile.csv','wb') as file:
for line in text:
file.write(line)
file.write('\n')
OR
Using CSV writer :
import csv
with open(<path to output_csv>, "wb") as csv_file:
writer = csv.writer(csv_file, delimiter=',')
for line in data:
writer.writerow(line)
OR
Simplest way:
f = open('csvfile.csv','w')
f.write('hi there\n') #Give your csv text here.
## Python will convert \n to os.linesep
f.close()
You could just write to the file as you would write any normal file.
with open('csvfile.csv','wb') as file:
for l in text:
file.write(l)
file.write('\n')
If just in case, it is a list of lists, you could directly use built-in csv module
import csv
with open("csvfile.csv", "wb") as file:
writer = csv.writer(file)
writer.writerows(text)
I would simply write each line to a file, since it's already in a CSV format:
write_file = "output.csv"
with open(write_file, "wt", encoding="utf-8") as output:
for line in text:
output.write(line + '\n')
I can't recall how to write lines with line-breaks at the moment, though :p
Also, you might like to take a look at this answer about write(), writelines(), and '\n'.
To complement the previous answers, I whipped up a quick class to write to CSV files. It makes it easier to manage and close open files and achieve consistency and cleaner code if you have to deal with multiple files.
class CSVWriter():
filename = None
fp = None
writer = None
def __init__(self, filename):
self.filename = filename
self.fp = open(self.filename, 'w', encoding='utf8')
self.writer = csv.writer(self.fp, delimiter=';', quotechar='"', quoting=csv.QUOTE_ALL, lineterminator='\n')
def close(self):
self.fp.close()
def write(self, elems):
self.writer.writerow(elems)
def size(self):
return os.path.getsize(self.filename)
def fname(self):
return self.filename
Example usage:
mycsv = CSVWriter('/tmp/test.csv')
mycsv.write((12,'green','apples'))
mycsv.write((7,'yellow','bananas'))
mycsv.close()
print("Written %d bytes to %s" % (mycsv.size(), mycsv.fname()))
Have fun
What about this:
with open("your_csv_file.csv", "w") as f:
f.write("\n".join(text))
str.join() Return a string which is the concatenation of the strings in iterable.
The separator between elements is
the string providing this method.
In my situation...
with open('UPRN.csv', 'w', newline='') as out_file:
writer = csv.writer(out_file)
writer.writerow(('Name', 'UPRN','ADMIN_AREA','TOWN','STREET','NAME_NUMBER'))
writer.writerows(lines)
you need to include the newline option in the open attribute and it will work
https://www.programiz.com/python-programming/writing-csv-files

Resources