Csv writer python no quotes

Python csv writer is adding quotes when not needed

Solution 1: You can easily format a string in any format you want: You can find more info in https://pyformat.info/ Solution 2: If you are using python3 which I assume you are from the question tags. Solution 3: You are turning list into string.

Python csv writer is adding quotes when not needed

I am having issues with writing json objects to a file using csv writer, the json objects seem to have multiple double quotes around them thus causing the json objects to become invalid, here is the result:

here is how I open the file, perhaps there is an argument I can pass to prevent this from happening?

file = csv.writer(open(localResultPath + ".txt",'ab'),delimiter = '|') 

here is how I write to the file, the last append adds the json as a string

list.append(pk) list.append(email) list.append(json) file.writerow(list) 

Switch off auto-quoting with quoting=csv.QUOTE_NONE , and set quotechar to the empty string:

file = csv.writer(open(localResultPath + ".txt",'ab'), delimiter='|', quoting=csv.QUOTE_NONE, quotechar='') 

Even with csv.QUOTE_NONE the csv.writer() will still want to quote the quotechar if left set to anything but an empty string, if present in the value. The default quote character is » and JSON values are full of those.

>>> from cStringIO import StringIO >>> import csv >>> f = StringIO() >>> writer = csv.writer(f, delimiter='|', quoting=csv.QUOTE_NONE, quotechar='') >>> writer.writerow(['']) >>> f.getvalue() '\r\n' 

You have to change the quotechar to s.th. else than » :

csv.writer(csvfile, delimiter='|',quotechar='&', quoting=csv.QUOTE_MINIMAL) 

Make sure that the quote character does not appear in your objects, obviously.

Читайте также:  Создание динамических страниц html

If you switch off quoting you have to be careful when your delimiter appears in the JSON-Object as well. Better way is using the json module and its functions json.dump() and json.load() for writing and reading the objects

Writing csv with quotes around strings (Python), Writing csv with quotes around strings (Python) Ask Question Asked 4 years, 9 months ago. Modified 1 year, 10 months ago. Viewed 6k times 4 1. I have written the following code to take a large csv file, and split it into multiple csv files based on a particular word in a column. The original csv file has some fields that are …

Writing to a file with no quotes, no commas in Python

I have the following code for writing my outputs to a file using Python.

ID= # type is dictionary=<> #Dictionary for item in dictionary.keys(): output=str([Question_ID,item,dictionary[item]]) target = open('result.relevancy', 'a') target.write(output+'\n') 

The output file is created as follows:

And I want to have only the plain text characters as an output as below:

(With no quotes, commas brackets)

You can easily format a string in any format you want:

output="%s %s %s" % (Question_ID, item, dictionary[item]) 

You can find more info in https://pyformat.info/

If you are using python3 which I assume you are from the question tags. I would suggest using the print command with the file argument

ID= # type is dictionary=<> #Dictionary for item in dictionary.keys(): print(Question_ID,item,dictionary[item],sep=' ',file=open('result.relevancy', 'a')) 

Although in a loop I think it would be wasting resources to open the file with every iteration so I would also suggest using a file context as follows.

ID= # type is dictionary=<> #Dictionary with open('result.relevancy', 'a') as fileOut: for item in dictionary.keys(): print(Question_ID,item,dictionary[item],sep=' ',file=fileOut) 

You are turning list into string. What you should do is:

output = ' '.join([str(i) for i in [Question_ID, item, dictionary[item]]) 
ID= # type is dictionary=<> #Dictionary for item in dictionary.keys(): output=str([Question_ID,item,dictionary[item]]) target = open('result.relevancy', 'a') target.write(output.replace("'", "") +'\n') 

Triple Quotes in Python, Spanning strings over multiple lines can be done using python’s triple quotes. It can also be used for long comments in code. Special characters like TABs, verbatim or NEWLINEs can also be used within the triple quotes. As the name suggests its syntax consists of three consecutive single or double-quotes. …

Adding qoute on YAML file from a dictionary

I have the following kind of dictionary:

I want to write this dictionary and get the YAML file using the following script.

with open('Table1.yaml', 'w') as f: yaml.dump(my_dict, f) 

The result that I got on the YAML file looks like the following:

table: description: Table 1 columns: - name: Column1 description: first column - name: Column2 description: second column - name: Column3 description: third column 

But I would like to get the description value in the quote below:

table: description: 'Table 1' columns: - name: Column1 description: 'first column' - name: Column2 description: 'second column' - name: Column3 description: 'third column' 

Can anyone help on how to add the quotes for every description key value?

import sys import yaml my_dict = < "table": < "description": "Table 1", "columns": [ , , , ], > > class SingleQuoted(str): pass def single_quoted_presenter(dumper, data): return dumper.represent_scalar("tag:yaml.org,2002:str", data, style="'") yaml.add_representer(SingleQuoted, single_quoted_presenter) def update_description(o): if isinstance(o, dict): for k, v in o.items(): if k == "description" and isinstance(v, str): o[k] = SingleQuoted(v) else: update_description(v) if isinstance(o, list): for v in o: update_description(v) update_description(my_dict) yaml.dump(my_dict, sys.stdout, sort_keys=False, default_flow_style=False) 
table: description: 'Table 1' columns: - name: Column1 description: 'first column' - name: Column2 description: 'second column' - name: Column3 description: 'third column' 

Set the default_style parameter.

yaml.dump(my_dict, f, default_style="'") 

You can read about the other parameters for example at https://realpython.com/python-yaml/#dumping-python-objects-to-yaml-documents.

import yaml my_dict = < 'table': < 'description': 'Table 1', 'columns': [ , , ] > > with open('Table1.yaml', 'w') as f: yaml.dump(my_dict, f, default_style="'") 

Adding text and lines to the beginning of a file (Python), f = open (‘file.txt’,’r+’) lines = f.readlines () # read old content f.seek (0) # go back to the beginning of the file f.write (new_content) # write new content at the beginning for line in lines: # write old content after new f.write (line) f.close ()

Writing to a specific column of a text file in python

I have an array of 6 string characters which are of the datatype string and I have to write them in 1,16,19,22,51,54th position of a line respectively in a text file using python to be properly read by a software.

[ABCD, 1, P, 15-06-2015, 0, Name of the account] 

The first element of the array is always a 4 or 5 letter string. (should start from 1st position of the line or first column of the line) The second element is always a single digit ( should start at 16) The third element is always a single alphabet (should start at 19) The fourth element is a date (should start at 22) The fifth element is again a single digit (should start at 51) The sixth element is a varying string which contains comments about the array (should start at 54)

Also after the sixth element there should be white spaces till 134th column

How can I do this in python automatically because I have to similarly write 200 lines.

This could be done with simple string formatting:

arr = ['ABCD', '1', 'P', '15-06-2015', '0', 'Name of the account'] print "".format(*arr) 

Values there are not positions but lengths of each item.

If items in your array are not only strings but also numbers it will still work, though you will probably want them left aligned (strings are by default):

arr = ['ABCD', 1, 'P', '15-06-2015', 0, 'Name of the account'] print "".format(*arr) 

I assume your «array» is a numpy array. If the formatting of your array is a strict as you say, then you should be able to write as follows:

# assume array is called A with open('filename.txt', 'r') as fid: for r in xrange(A.shape[0]): A[r].tofile(fid, sep=', ') 

If your array is really a list:

with open('filename.txt', 'r') as fid: for r in A: fid.write( ', '.join(r) ) 

Of course, this depends on your array containing only strings. I understand you said that there are strings, integers, and dates, within your array, but I assume you mean they are all strings. If that is not the case, then you can correct for this by including a simple type conversion in the loops.

Writing double quotes in python, Add a comment | 3 Answers Or with simple quotes: file.write(‘Item «‘ + Name[i] + ‘» ‘) Or with triple double quotes and string interpolation: There are many many ways to declare string literals in Python Share. Follow edited Mar 21, 2011 at 9:08. answered Mar 15, 2011 at 6:12. glmxndr glmxndr. 44.2k 27 27 gold badges 92 92 … Usage examplefile.write(‘Item «<0>«‘.format(name[i]))Feedback

Источник

Оцените статью