Running Json file in VScode using Python - python

I am very fresh in Python. I would like to read JSON files in Python, but I did not get what are the problems. Please see the image.

You have to specify a mode to the open() function. In this case I think you're trying to read the file, so your mode would be "r". Your code should be:
with open(r'path/to/read/','r') as file:
data = json.load(file)
Your code should run now.

Your path should not contain spaces. Please modify the file path.
Generally speaking, the file path is best to be in full English with no spaces and no special characters.

import sys
import os
import json
def JsonRead(str):
with open(str, encoding='utf-8') as f:
data = json.load(f)
return data
new_Data = JsonRead(filePath)
Then import JsonRead in project

Related

Edit Minecraft .dat File in Python

I'm looking to edit a Minecraft Windows 10 level.dat file in python. I've tried using the package nbt and pyanvil but get the error OSError: Not a gzipped file. If I print open("level.dat", "rb").read() I get a lot of nonsensical data. It seems like it needs to be decoded somehow, but I don't know what decoding it needs. How can I open (and ideally edit) one of these files?
To read data just do :
from nbt import nbt
nbtfile = nbt.NBTFile("level.dat", 'rb')
print(nbtfile) # Here you should get a TAG_Compound('Data')
print(nbtfile["Data"].tag_info()) # Data came from the line above
for tag in nbtfile["Data"].tags: # This loop will show us each entry
print(tag.tag_info())
As for editing :
# Writing data (changing the difficulty value
nbtfile["Data"]["Difficulty"].value = 2
print(nbtfile["Data"]["Difficulty"].tag_info())
nbtfile.write_file("level.dat")
EDIT:
It looks like Mojang doesn't use the same formatting for Java and bedrock, as bedrock's level.dat file is stored in little endian format and uses non-compressed UTF-8.
As an alternative, Amulet-Nbt is supposed to be a Python library written in Cython for reading and editing NBT files (supposedly works with Bedrock too).
Nbtlib also seems to work, as long as you set byteorder="little when loading the file.
Let me know if u need more help...
You'll have to give the path either relative to the current working directory
path/to/file.dat
Or you can use the absolute path to the file
C:user/dir/path/to/file.dat
Read the data,replace the values and then write it
# Read in the file
with open('file.dat', 'r') as file :
filedata = file.read()
# Replace the target string
filedata = filedata.replace('yuor replacement or edit')
# Write the file out again
with open('file.dat', 'w') as file:
file.write(filedata)

Python - Remove special character from csv file import into PostgreSQL

I would like to import my csv file into Postgresql using Python.
The import works well. However, when I display the imported data, I find a special symbol on the first line and first column.
I tried to solve the problem by adding the encoding in my python code but nothing has to do.
Here is my code:
import sys
import os
import csv
import io
f = io.open(r'C:\\list.csv', mode='r', encoding='utf-8')
curs.copy_from(f, 'list', sep=';')
conn.commit()
Here is the symbol or special character:

Thank you
You are picking up the Byte order mark.
In order to have the io module expect and strip off the BOM try changing your encoding to utf-8-sig:
f = io.open(r'C:\\list.csv', mode='r', encoding='utf-8-sig')
More info here.

Syntax Error when importing a text file containing a dictionary

import ast
dict_from_file=[]
with open('4.txt', 'r') as inf:
dict_from_file = ast.literal_eval(inf.read())
File "<unknown>", line 1
["hello":"work", "please":"work"]
^
SyntaxError: invalid character in identifier
Hi Everyone! The above is my code and my error. I have a really complicated 40MB data file in the form of a dictionary to work on, but couldn't get that import to work so tried a simple one.
I'm using the latest Jupyter notebook from the latest version of Anaconda, on Windows 10. My dictionary is a txt file created using windows notepad. The complicated dictionary was originally a JSON file that I changed into a txt file thinking it would be easier but I may be wrong.
I think the above error is an encoding issue? But not sure how to fix it.
Thanks!
If you are the owner/write of the file (dict formated), save as json
import json
#To write
your_dict = {.....}
with open("file_name.txt", "w+") as f:
f.write(json.dumps(your_dict)
#To read
with open("file_name.txt") as f:
read_dict = json.load(f)
This is possibly a python 3 "feature".
This code removes the unwanted characters at the start of the input file and returns the input data as type string.
with open('4.txt', 'r',,encoding="utf-8-sig") as inf:
dict_from_file = ast.literal_eval(inf.read())
This removes the strange characters put at the beginning of read data.

Python cannot see csv file

I went through couple answers on forum already but without any success.
I am using Linux mint, Python 3.6.0 and i am trying to open CSV in Python but then error occurs:
file = open("~/Desktop/xyz/city.csv", "rb")
FileNotFoundError: [Errno 2] No such file or directory: '~/Desktop/xyz/city.csv'
My code:
import csv
file = open("~/Desktop/xyz/city.csv", "rb")
reader =csv.reader(file)
I also tried to move the file to desktop as in some answers i found, instead of path i used "city.csv". Still doesn't work.
Completely new to Linux and just can't find why this isn't working.
Each reply appreciated!
You should'nt use '~' to specify the path of your directory but the full path instead. E.g. :
import csv
file = open("/home/user/Desktop/xyz/city.csv", "rb")
reader =csv.reader(file)
If you need to use the tilde, you should then use os.path.expanduser('~/Desktop/xyz/city.csv'). E. g. :
import csv
file = open(os.path.expanduser("~/Desktop/xyz/city.csv"), "rb")
reader =csv.reader(file)
The reason for that is that the "tilde expansion" is a user interface feature that is not recognized by the file system: http://www.gnu.org/software/bash/manual/bashref.html#Tilde-Expansion
Try using the full file path, something like this:
file = open("/home/[username]/Desktop/xyz/city.csv", "rb")
Usually ~ does not expand properly. I have found that when it is needed, put $HOME environment variable value into a python variable and then use join to attach it as a prefix to the file name relative position. This also allows you to move the file to a different location and create a function that will allow you to redefine the prefix.

importing external ".txt" file in python

I am trying to import a text with a list about 10 words.
import words.txt
That doesn't work...
Anyway, Can I import the file without this showing up?
Traceback (most recent call last):
File "D:/python/p1.py", line 9, in <module>
import words.txt
ImportError: No module named 'words'
Any sort of help is appreciated.
You can import modules but not text files. If you want to print the content do the following:
Open a text file for reading:
f = open('words.txt', 'r')
Store content in a variable:
content = f.read()
Print content of this file:
print(content)
After you're done close a file:
f.close()
As you can't import a .txt file, I would suggest to read words this way.
list_ = open("world.txt").read().split()
The "import" keyword is for attaching python definitions that are created external to the current python program. So in your case, where you just want to read a file with some text in it, use:
text = open("words.txt", "rb").read()
This answer is modified from infrared's answer at Splitting large text file by a delimiter in Python
with open('words.txt') as fp:
contents = fp.read()
for entry in contents:
# do something with entry
numpy's genfromtxt or loadtxt is what I use:
import numpy as np
...
wordset = np.genfromtxt(fname='words.txt')
This got me headed in the right direction and solved my problem.
Import gives you access to other modules in your program. You can't decide to import a text file. If you want to read from a file that's in the same directory, you can look at this. Here's another StackOverflow post about it.

Categories

Resources