Adding 'r' to json string from file python [duplicate] - python

This question already has answers here:
Convert regular Python string to raw string
(12 answers)
Closed 3 years ago.
I am facing with the following error while reading json from file
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 2 column 1 (char 948)
The json content is read from file using the script below
import json
if __name__ == "__main__":
file_path = "D:\\Freelancing\\Scraping_football_historic_data\\Data\\1.138103502"
with open(file_path,'r') as datafile:
dict_data = json.load(datafile)
print(dict_data)
Upon searching for answer, this question had an answer that suggested me to add r before the json string.
How can it be done in the case above, or if there's a better way to read the file. ?
The contents of the file can be read from the pastebin link:
https://pastebin.com/ZyyrtcZW

You are missing a comma between each of your individual dictionaries, your data should look like
....
{"op":"mcm","clk":"5733948534","pt":1514206953689,"mc":[{"id":"1.138103502","rc":[{"ltp":2.02,"id":48756}]}]},
{"op":"mcm","clk":"5739085003","pt":1514309273736,"mc":[{"id":"1.138103502","rc":[{"ltp":2.0,"id":48756}]}]},
{"op":"mcm","clk":"5739711407","pt":1514327265235,"mc":[{"id":"1.138103502","rc":[{"ltp":2.06,"id":48756}]}]},
.....

Related

what is the fgets() equivalent in Python [duplicate]

This question already has answers here:
Read only the first line of a file?
(8 answers)
Closed 3 months ago.
I am currently working with file handling in Python.
I have problem in copying the string value of the file.
I wanted to copy the string from file and store it to a variable, just like in C
example: this is how we do in C
FILE *fptr = fopen("read.txt", "r");
fgets(charVar, 100, fptr);
where we store the string file to charVar.
So is there a fgets() function equivalent to python?
You can pass the limit argument to readline for a file object which would have similar behavior of stopping on a max character or a newline. Example text file:
01234567890123456789
01234567890123456789
with open("test.txt", "r") as f:
while data := f.readline(8):
print("line:", data)
Outputs:
line: 01234567
line: 89012345
line: 6789
line: 01234567
line: 89012345
line: 6789

Python - How to convert dictionary alike string to dictionary [duplicate]

This question already has answers here:
Convert a String representation of a Dictionary to a dictionary
(11 answers)
How to convert JSON data into a Python object?
(33 answers)
Closed 2 years ago.
I have a string as below
"{"V":1,"Batch":10001,"File":"abc.csv","ContactorID":"A001"}"
How can I actually convert this string to a dictionary? The string originate from a txt file
You should use the json module. You can either open the file and use json.load(file) or include the text as a string in your program and do json.loads(text). For example:
import json
with open('file.txt', 'r') as file:
dict_from_file = json.load(file)
or
import json
text = '{"V":1,"Batch":10001,"File":"abc.csv","ContactorID":"A001"}'
dict_from_text = json.loads(text)
For more info see https://realpython.com/python-json/.

How to convert python code in a text file to python code inside a program [duplicate]

This question already has answers here:
How can I parse (read) and use JSON?
(5 answers)
Closed 2 years ago.
So I have a text file with the text below:
{'Maps': {'Usefulness':80,'Accesibility':70,'Popularity':90}
(the dictionary carries on that's why there may be a few syntax issues)
How do I convert this text into python code inside my program?
eg:
if the text files name is x.txt
textfile = convert(x.txt)
print(list(textfile.keys()))
the output would look something like
['Maps','Drive','Chrome']
You can use ast.literal_eval to evaluate a string (like the one you get from reading a text file) as Python code:
import ast
s = """{
'Maps': {
'Usefulness':80,
'Accesibility':70,
'Popularity':90
}
}"""
ast.literal_eval(s)
# output: {'Maps': {'Usefulness': 80, 'Accesibility': 70, 'Popularity': 90}}
Reading from a text file:
with open('file.txt', 'r') as file:
result = ast.literal_eval(file.read())
print(list(result.keys()))
If your text file is just a dictionary you can also use the json module. But the more generalist answer is to use ast.literal_eval.
You should use the json module
import json
with open('x.txt') as json_file:
data = json.load(json_file)
print(data.keys)

Why does my first element in readlines() of a CSV have additional characters? [duplicate]

This question already has answers here:
Reading Unicode file data with BOM chars in Python
(7 answers)
Closed 4 years ago.
I ran the following python code to open a CSV, and the first element had some extra characters in it that aren't present when I view the CSV in a text editor, say Notepad++.
priorities_file = open('priorities.txt', 'r')
print('Name of the file: ', priorities_file.name)
p = priorities_file.readlines()
print('Read Line: %s' % (p))
The output looked like this:
Name of the file: priorities.txt
Read Line: ['Autonomy\n', 'Travel\n',...
I understand the '\n' and how to remove that from each element, but I don't understand why there are the additional characters in front of the element ' Autonomy'. Can anyone tell me why this is? Bonus points for a way to remove those characters which I honestly couldn't find how to reproduce.
repr() would help. (on Python 3.X; use ascii() instead).
p = priorities_file.readlines()
print(repr(p))
My hunch is that the ecnoding in the csv file is not actually ASCII or UTF8?
UPDATE:
This should do the trick:
p = p.decode("utf-8-sig")

Writing Russian characters to txt file using python [duplicate]

This question already has answers here:
Writing Unicode text to a text file?
(8 answers)
Closed 6 years ago.
I try to write to txt file list with russian string.(I get that with unique1 = np.unique(df['search_term']), it's numpy.ndarray)
thefile = open('search_term.txt', 'w')
for item in unique1:
thefile.write("%s\n" % item)
But in list this string looks correct. But after writing it looks like
предметов berger bg bg045-14 отзывы
звезд
воронеж
Why a get that?
Try writing to the file like this:
import codecs
thefile = codecs.open('search_term.txt', 'w', encoding='utf-8')
for item in unique1:
thefile.write("%s\n" % item)
The problem is that the file likely is encoded correctly hence why the characters will display incorrectly.

Categories

Resources