How do I setup a loop that convert the dictionary into string? - python

So, I do have the excel csv file. and I need to change the dictionary into string. How do I do that? The purpose of my assignment is It writes the contents of a database1 dictionary back to a CSV file in the same format
as it was the original input file
Original file name is vt.csv
I know I have to set up a loop that converts the dictionary into string but I just can't figure out how. Please help.#I have to use this format
def write_vt(db, filename):
file = open('new_vt.csv', 'w')

This works:
with open(filename, 'r') as f:
str = f.read()
You don't need the csv module.

Related

How to create and use a text file in Python?

I need to create a text file in Python to store certain data from a game. I do not want to use numpy, or any external libraries if at all possible.
I need to put some numerical data. Do text files require string data? Also does the data come out of the file as a string?
I know how to create and open a text file, and how to convert string to integer and vice versa, as well as handle CSV file data. I do not know how to handle a text file.
Any ideas on what to do?
To create a file:
file = open("textfile.txt","w+")
This will create a file if it doesn't exist in the directory.
To write inside it:
file.write("This is the content of the file.")
And then you'll have to close the instance with
file.close()
by using the with open command you can create and use it
here is an example
Here w is for writing mode
with open('test.txt','w') as d:
d.write('your text goes here')
You can write to file like this if the file not exists then it will be created
Any ideas on what to do?
Put your data into dict and use built-in json module, example:
import json
data = {'gold': 500, 'name': 'xyzzy'}
# writing
with open('save.json', 'w') as f:
json.dump(data, f)
# reading
with open('save.json', 'r') as f:
data2 = json.load(f)
This create human-readable text file.

Parse a file of strings in python separated by newline into a json array

I have a file called path_text.txt its contents are the 2 strings separated by newline:
/gp/oi/eu/gatk/inputs/NA12878_24RG_med.hg38.bam
/gp/oi/eu/gatk/inputs/NA12878_24RG_small.hg38.bam
I would like to have a json array object like this:
["/gp/oi/eu/gatk/inputs/NA12878_24RG_med.hg38.bam","/gp/oi/eu/gatk/inputs/NA12878_24RG_small.hg38.bam"]
I have tried something like this:
with open('path_text.txt','w',encoding='utf-8') as myfile:
myfile.write(','.join('\n'))
But it does not work
I don't see where you're actually reading from the file in the first place. You have to actually read your path_text.txt before you can format it correctly right?
with open('path_text.txt','r',encoding='utf-8') as myfile:
content = myfiel.read().splitlines()
Which will give you ['/gp/oi/eu/gatk/inputs/NA12878_24RG_med.hg38.bam', '/gp/oi/eu/gatk/inputs/NA12878_24RG_small.hg38.bam'] in content.
Now if you want to write this data to a file in the format ["/gp/oi/eu/gatk/inputs/NA12878_24RG_med.hg38.bam", "/gp/oi/eu/gatk/inputs/NA12878_24RG_small.hg38.bam"]-
import json
with open('path_json.json', 'w') as f:
json.dump(content, f)
Now the path_json.json file looks like-
["/gp/oi/eu/gatk/inputs/NA12878_24RG_med.hg38.bam", "/gp/oi/eu/gatk/inputs/NA12878_24RG_small.hg38.bam"]
which is valid json in case you want to load a json from a file
see below
with open('path_text.txt') as f:
data = [l.strip() for l in f.readlines()]

How to convert a series of JSON strings into one json file?

I am using python and json to construct a json file. I have a string, 'outputString' which consists of multiple lines of dictionaries turned into jsons, in the following format:
{size:1, title:"Hello", space:0}
{size:21, title:"World", space:10}
{size:3, title:"Goodbye", space:20}
I would like to turn this string of jsons and write a new json file entirely, with each item still being its own line. I would like to turn the string of multiple json objects and turn it into one json file. I have attached the code on how I got outputString and what I have tried to do. Right now, the code I have writes the file, but all on one line. I would like the lines to be separated as the string is.
for value in outputList:
newOutputString = json.dumps(value)
outputString += (newOutputString + "\n")
with open('data.json', 'w') as outfile:
for item in outputString.splitlines():
json.dump(item, outfile)
json.dump("\n",outfile)
PROBLEM: when you json.dump("\n",outfile) it will always be written on the same line as ”\n” is not recognised as a new line in json.
SOLUTION: ensure that you write a new line using python and not a json encoded string:
with open('data.json', 'a') as outfile: # We are appending to the file so that we can add multiple new lines for each of different json strings
for item in outputString.splitlines():
json.dump(item, outfile)
outfile.write("\n”) # write to the file a new line, as you can see this uses a python string, no need to encode with json
See comments for explanation.
Please ensure that the file you write to is empty if you just want these json objects in them.
Your value rows are not in actual json format if the properties do not come between double quotes.
This would be a proper json data format:
{"size":1, "title":"Hello", "space":0}
Having said that here is a solution to your question with the type of data you provided.
I am assuming your data comes like this:
outputList = ['{size:1, title:"Hello", space:0}',
'{size:21, title:"World", space:10}',
'{size:3, title:"Goodbye", space:20}']
so the only thing you need to do is write each value using the file.write() function
Python 3.6 and above:
with open('data.json', 'w') as outfile:
for value in outputList:
outfile.write(f"{value}\n")
Python 3.5 and below:
with open('data.json', 'w') as outfile:
for value in outputList:
outfile.write(value+"\n")
data.json file will look like this:
{size:1, title:"Hello", space:0}
{size:21, title:"World", space:10}
{size:3, title:"Goodbye", space:20}
Note: As someone already commented, your data.json file will not be a true json format ted file but it serves the purpose of your question. Enjoy! :)

How can I read a file that contains a list of dictionaries into python?

I've created a file that contains a list of dictionaries that I was working with. Unfortunately, I'm not sure how to re-import that file back into python in that same format.
I initially wrote the file out as JSON and as text, like this:
d = list_of_dics
jsonarray = json.dumps(d)
with open('list_of_dics.txt', 'w') as outfile:
json.dump(jsonarray, outfile)
with open('list_of_dics.json', 'w') as outfile:
json.dump(jsonarray, outfile)
Can anyone suggest a way to re-import these into python in the same format — i.e., a list of dictionaries?
You're using json.dump() incorrectly. You should be passing d to it directly, not the output of json.dumps(d). Once you do that, you can use json.load() to retrieve your data.
with open('list_of_dics.txt', 'r') as infile:
d = json.load(infile)
With
json.dumps(d)
you've (JSON-)encoded list d in a string (which you assign to a variable misleadingly called jsonarray).
With
json.dump(jsonarray, outfile)
you've JSON-encoded that string and written the result to outfile.
So it's now (unnecessarily) doubly JSON-encoded in the files list_of_dics.txt and list_of_dics.json.
To cleanly get it back from there (without resorting to manual string manipulation) you have to decode it twice:
import json
with open('list_of_dics.json', 'r') as infile:
recovered_d = json.loads(json.load(infile))

Write a complete list into a text file in Python

I got a list like this that I got reading a temporary text file before.
['Usain','Jamaican','9','2','0']
But now I need to write this list into a new text file that contains a list with lists. The text file should look like this:
[['Usain','Jamaican','9','2','0'], ['Christopher', 'Costarican', '0','1',2']]
I've tried to write the list into a text file, but I just import the elements on the list and write them as newlines.
my code looks like this
def terminar():
with open('temp.txt', 'r') as f:
registroFinal = [line.strip() for line in f]
final = open('final.txt','a')
for item in registroFinal:
final.write("%s\n" % item)
os.remove('temp.txt')
You can use json to dump out the list of lists:
import json
with open('final.txt','a') as final:
json.dump(registroFinal, final)
You would load this in with json.load(). Otherwise you could use repr(registroFinal) to write out the representation into a file. How is this data going to be used? If you plan to read it back into a python object I would favour the json approach.
Python also has the facility to manage temporary files, see tempfile module

Categories