How to input a JSON file an print a line - python

Write a program that inputs a JSON file (format just like
example1.json) and prints out the value of the title field.
import json
# TODO: Read your json file here and return the contents
def read_json(filename):
dt = {}
# read the file and store the contents in the variable 'dt'
with open(filename,"r") as fh:
dt = json.load(fh)
###fh = open(filename, "r")
###dt = json.load(fh)
return dt
# TODO: Pass the json file here and print the value of title field. Remove the `pass` statement
def print_title(dt):
print filename["title"]
# TODO: Input a file from the user
filename = raw_input("Enter the JSON file: ")
# The function calls are already done for you
r = read_json(filename)
print_title(r)
Hi, I'm new with Python and I'm not sure what I am doing wrong. I keep getting the following message:
enter image description here

Your'e almost there, you just confused with the parameter name.
Change this:
def print_title(dt):
print filename["title"]
To:
def print_title(dt):
print dt["title"]

Related

Python - define a function to manage files

I need to define a fucntion that will, in short:
Open and grab the content from an existing file
Transform that content
Create a new file
Write that new content in this new file
Print the content of the new file
I'm a complete begginer, but I got this until now. How can I improve this?
def text():
#open the existing file
text_file = open('music.txt', 'r')
#reads the file
reading = text_file.read ()
#this turns everything to lower case, counts the words and displays the list vertically
from collections import Counter
new_text = reading.lower()
list_words = Counter(new_text.split())
ordered_list = sorted(list_words.items())
#creates a new file and writes the content there
with open('finheiro_saida.txt', 'x') as final_file:
for i in ordem:
finheiro_saida.write(str(i) + '\n')
#not sure how to open this new file and print its content, when I tried it says the new file doesn't exist in the directory - tried everything.
final = open('C:/Users/maria/OneDrive/Documents/SD_DTM/ficheiro_saida.txt', 'r')
read_file = final.read ()
print(read_file)
You can open the new file and print its content the same way you read and wrote to it!
# ...After all your previous code...
with open('finheiro_saida.txt', 'r') as final_file:
final_file_content = final_file.read()
print(final_file_content)
Fixed some syntax error in your code.
you can display the the same way you read.
Also provide all imports to the start of the file.
you can also read all lines from the file as a list using file.readlines()
from collections import Counter
def text():
# open the existing file
text_file = open("music.txt", "r")
# reads the file
reading = text_file.read()
# this turns everything to lower case, counts the words and displays the list vertically
new_text = reading.lower()
list_words = Counter(new_text.split())
ordered_list = sorted(list_words.items())
# creates a new file and writes the content there
file_name = "finheiro_saida.txt"
with open("finheiro_saida.txt", "x") as final_file:
for i in ordered_list:
final_file.write(str(i) + "\n")
return file_name
def display(final_file_name):
with open(final_file_name) as file:
print(file.read())
final_file_name = text()
display(final_file_name)

How to pass a text file as an argument to a function in python

Here is the code and I am trying to see what I have done wrong. I am new to python functions and linking external files so it would be nice if you could explain your code.
def get_data(filename):
records = []
with open(filename) as readfile:
lines = readfile.readlines()
for line in lines:
# variable line contains:
str_rec = line.split(",")
pname = str_rec[0]
price = int(str_rec[1])
quantity = int(str_rec[2])
records.append([pname, price, quantity])
#caution: indentation
return records
hell= get_data(data.txt)
print(hell)
data.txt is a link to another file that I am trying to pass as an argument.
open(filename) takes the filename as a string, so you should pass the name as a string, not the actual file.
hell= get_data("data.txt")

How to dump data into Json file using python

How to dump data into Json file
*as can see in the below python code I am trying the dump data in Json file so but I am struggling to do it in python code *
import time
import json
import os
def long_function(name):
cache_path = 'cache.json'
if not os.path.isfile(cache_path):
with open(cache_path, 't') as json_file:
cache_file_data = [name]
jsondump(cache_file_data, json_file)
else:
with open(cache_path, 'r') as json_file:
cache_file_data = json.load(json_file)
if name in cache_file_data:
print("Name already exist")
return name
else:
cache_file_data.append(name)
for e in range(5):
time.sleep(1)
print(e+1)
with open(cache_path, 'w') as json_file:
jsondump(cache_file_data, json_file)
print("New Name added in cache")
return name
print(long_function('nitu'))
so please resolve my problem......please help me
import json
# JSON data:
x = '{ "organization":"New_holn",
"city":"Noida",
"country":"India"}'
# python object to be appended
y = {"pin":117845}
# parsing JSON string:
z = json.loads(x)
# appending the data
z.update(y)
# the result is a JSON string:
print(json.dumps(z))
This is nothing but follow this pattern and your so your code error is ..you are not defined file mode correctly in if condition
with open (cache_path. "t") as json_file:
Instead of
with open (cache_path. "w") as json_file:
And second thing is you are not doing dump data

Python Error:Can't convert 'list' object to str implicitly while writing to a json file

I have a json file out of which one field has list data as shown below
{
"broker_address":"0.0.0.0",
"serial_id": "YYMMSSSSSSVV",
"auto_foc": true,
"timer": [0,23,30]
}
I am taking user input for timer field so I want to replace the timer data with the input value received from user. On trying it I am getting following error
Traceback (most recent call last):
File "test.py", line 23, in <module>
time, final)
TypeError: Can't convert 'list' object to str implicitly
My code snippet is as follows
import json
import os
import time
val = input("Enter your value: ")
print(val)
str1 = " "
with open('/home/pi/config.json', 'r+') as filer:
print("file read")
az = filer.read()
print(az)
read_file = az.rstrip('/n')
data = json.loads(read_file)
#print("printing file",json.loads(read_file))
time=data["timer"]
#print(read_file)
print(time)
print("Waiting.....................")
#time.sleep(2)
final = str(val)
print(final)
read_file = read_file.replace(
time, final)
with open('/home/pi/config.json', 'w') as filer:
filer.write(read_file)
Please let me know how to resolve this error.
Try this:
import json
import os
import time
val = input("Enter your value: ")
print(val)
str1 = " "
with open('/home/pi/config.json', 'r+') as filer:
print("file read")
az = filer.read()
print(az)
read_file = az.rstrip('/n')
data = json.loads(read_file)
#print("printing file",json.loads(read_file))
time=data["timer"]
#print(read_file)
print(time)
print("Waiting.....................")
#time.sleep(2)
final = str(val).split()
final = [int(i) for i in final]
print(final)
print(str(time))
read_file = read_file.replace(str(time), str(final))
print(read_file)
with open('/home/pi/config.json', 'w') as filer:
filer.write(read_file)
And update the json file from "timer": [0,23,30] to "timer": [0, 23, 30] i.e. add spaces
One thing avoid using the name time when you use that name as a variable it will replace the imported name time. Secondly the issue is that the data is a list not a string and replace is expecting a string not a list.
What you will want to do is just take advantage of json for what it is a serializer and deserializer and modify the data itself and use json to write it to a file. This also ensures you will be able to read it back out as json.
import json
import os
import time
val = input("Enter your value: ")
print(val)
str1 = " "
with open('/home/pi/config.json', 'r+') as filer:
print("file read")
data = json.load(filer)
timer=data["timer"] #DONT USE time
print(timer)
print("Waiting.....................")
#time.sleep(2)
final = str(val)
print(final)
#This next part will be up to you,
# do you want this to be the list it was before?
# or the string as input
data['timer'] = final
with open('/home/pi/config.json', 'w') as filer:
json.dump(data,filer)

How can I open and read an input file and print it to an output file in Python?

So how can I ask the user to provide me with an input file and an output file?
I want the content inside the input file provided by the user to print into the output file the user provided. In this case, the user would put in this
Enter the input file name: copyFrom.txt
Enter the output file name: copyTo.txt
inside the input file is just the text "hello world".
Thanks. Please keep it as simple as you can if possible
If you just want to copy the file, shutil’s copy file does the loop implicitly:
import os
from shutil import copyfile
openfile = input('Enter the input file name:')
outputfile = input('Enter the output file name:')
copyfile(openfile, outputfile)
This this post How do I copy a file in Python? for more detail
Here is an example that should work in Python3. The input and output file names would need to include the full path (i.e. "/foo/bar/file.txt"
import os
input_file = input('Enter the input file name: ')
output_file = input('Enter the output file name: ')
def update_file(input_file, output_file):
try:
if os.path.exists(input_file):
input_fh = open(input_file, 'r')
contents = input_fh.readlines()
input_fh.close()
line_length = len(contents)
delim = ''
if line_length >= 1:
formatted_contents = delim.join(contents)
output_fh = open(output_file, 'w')
output_fh.write(formatted_contents)
output_fh.close()
print('Update operation completed successfully')
except IOError:
print(f'error occurred trying to read the file {input_fh}')
update_file(input_file, output_file)
You can do this...
import os
openfile = input('Enter the input file name:')
outputfile = input('Enter the output file name:')
if os.path.isfile(openfile):
file = open(openfile,'r')
output = open(outputfile,'w+')
output.write(file.read())
print('File written')
exit()
print('Origin file does not exists.')
To input the input-file and output-file names, simply use the input(s) function where s is the input message.
To get the "content inside the input file provided by the user to print into the output file," that would mean reading the input file and writing the read data into the output file.
To read the input file, use f = open(input_filename, 'r'), where the first argument is the filename and the second argument is the open mode where 'r' means read. Then letting readtext be the read text information of the input file, use readtext = f.read(): this returns the entire text content of f.
To output the read content to the output file, use g = open(output_filename, 'w'), noting that now the second argument is 'w', meaning write. To write the data, use g.write(readtext).
Please note that an exception will be raised if the input file is not found or the output file is invalid or not possible as of now. To handle these exceptions, use a try-except block.
This is effectively a file-copying operation in Python. shutil can serve as a useful alternative.
First you have to read the file and save it to some variable (here rd_data):
if os.path.exists(input_file_name):
f = open(input_file_name,"r")
rd_data = f.read()
f.close()
Then you have to write the variable to other file:
f = open(output_file_name,"w")
f.write(rd_data)
f.close()
The full code is given below:
import os
input_file_name = input("Enter file name to read: ")
output_file_name = input("Enter file name to write: ")
if os.path.exists(input_file_name):
f = open(input_file_name,"r")
rd_data = f.read()
f.close()
f = open(output_file_name,"w")
f.write(rd_data)
f.close()

Categories

Resources