This exampleillustrates how to read from both a string and a JSON file. Initially, we have a JSON string stored in the variable 'jsonString'. We convert this JSON string into a Python dictionary using json.loads() method, which is then stored in the variable 'jsonDict'. Next, we read a JSON string stored in a file using json.loads(). To achieve this, we first convert the JSON file into a string using file handling, similar to the previous example. Then, we convert it into a string using the read() function. The subsequent steps mirror those followed earlier, utilizing the json.loads() method.
2 snippets
import os
import uuid
filename = str(uuid.uuid4()) # create random file name
wLines = ["First line\n", "Second line\n", "Third line\n"]
# writing lines to file
f = open(filename, 'w')
f.writelines(wLines)
f.close()
#--------------------------------------------------------#
print("-----Read lines using 'readlines' method-----")
f = open(filename, 'r')
rLines = f.readlines()
for lineNumber, line in enumerate(rLines, 1):
print("Line {}: {}".format(lineNumber, line.strip()))
#--------------------------------------------------------#
print("-----Read lines using 'readline' method-----")
f = open(filename, 'r')
lineNumber = 1
while True:
lineNumber += 1
# Get next line from file
line = f.readline()
# if line is empty
# end of file is reached
if not line:
break
print("Line {}: {}".format(lineNumber, line.strip()))
f.close()
#--------------------------------------------------------#
print("-----Read lines via file object iteration-----")
f = open(filename, 'r')
for lineNumber, line in enumerate(f, 1):
print("Line {}: {}".format(lineNumber, line.strip()))
#--------------------------------------------------------#
print("-----Read lines via file contex manager-----")
with open(filename, "r") as f:
for lineNumber, line in enumerate(f, 1):
print("Line {}: {}".format(lineNumber, line.strip()))
os.remove(filename) # remove file
# Output example:
# Read lines using 'readlines' method
# Line 1: First line
# Line 2: Second line
# Line 3: Third line
Here's an example of reading from a file line by line in Python.
0 Burnfires
0
Snippets46
Categories0
Tags62
Users3