I'm trying to add previously added integers in the json file. for discord.py
#client.command()
async def mine(ctx):
await open_account(ctx.author)
users = await get_wallet_data()
user = ctx.author
earnings = int(random.randrange(11))
em = discord.Embed(title = 'Mined NeoCoins')
em.add_field(name = 'Earnings:', value = earnings)
await ctx.send(embed = em)
wallet_amt = users[str(user.id)]['Wallet']
print(wallet_amt)
nw = wallet_amt =+ earnings
nw = users[str(user.id)]['Wallet']
print(nw)
with open('wallet.json','w') as f:
users = json.dump(users,f)
But I'm getting that same value. Not the added value
To change the values of .json files, you have to load the file first, make the edits, and then replace the file with the changed version.
Load file:
with open("filename.json", "w+") as fp:
d = json.load(fp) #load the file as an object
Make edits:
... #change the values in d
Replace file with changed version:
fp.truncate(0) #empty the file
json.dump(d, fp) #dump changed version into file
Full Code
Related
I'm trying to manipulate a config file that will look like this:
[DEFAULT]
first_api_key = foobar
second_api_key = helloworld
Now say I'd like to replace first_api_key with "guccimane" instead of "foobar". Here's the function I'm using to do that:
def my_func():
k, v = "first_api_key", "guccimane"
file = os.path.join("/example/path", "settings.ini")
config = configparser.ConfigParser()
with open(file, "w") as f:
config.read(file)
config["DEFAULT"][k] = v
config.write(f)
However when I run that, second_api_key is removed and I'm left with:
[DEFAULT]
first_api_key = foobar
However when I change my function slightly to be:
def my_func():
k, v = "first_api_key", "guccimane"
file = os.path.join("/example/path", "settings.ini")
config = configparser.ConfigParser()
config.read(file)
with open(file, "w") as f:
config["DEFAULT"][k] = v
config.write(f)
It works exactly the way I want it to, and it only alters the first_api_key value and the second_api_key remains. Does anyone know why this is getting overwritten?
i want to read the whole pdf content.
I have used PyPDF2 and iterate pages through numpgaes object using for loop.
but my problem is i only able to get the whole document text only inside the for loop.
but i want to use it outside the loop. what should i do?
my code is look like below.
import PyPDF2
sample_pdf = open(r'/home/user/Desktop/123.pdf', mode='rb')
pdfdoc = PyPDF2.PdfFileReader(sample_pdf)
x = ''
for i in range(pdfdoc.numPages):
current_page = pdfdoc.getPage(i)
text = current_page.extractText()
x = text
I am getting whole pdf content in variable text but in x variable i am only getting last page content.
Have you tried using a list?
import PyPDF2
sample_pdf = open(r'/home/user/Desktop/123.pdf', mode='rb')
pdfdoc = PyPDF2.PdfFileReader(sample_pdf)
x = []
for i in range(pdfdoc.numPages):
current_page = pdfdoc.getPage(i)
text = current_page.extractText()
x.append(text)
The addition of string gives me the expected results.
import PyPDF2
sample_pdf = open(r'/home/user/Desktop/123.pdf', mode='rb')
pdfdoc = PyPDF2.PdfFileReader(sample_pdf)
x = ''
for i in range(pdfdoc.numPages):
current_page = pdfdoc.getPage(i)
text = current_page.extractText()
x += str(text)
print(x)
I built a form with a FileField in order to upload file to be processed. Strangely it seem that file is closed before I can do anything with in the view. I encounter a ValueError after validating the form:
"I/O operation on closed file"
I can see that file is properly detected but closed when attempting to read it.
Note: Django version 2.2.25.
forms.py
class FileImportForm(forms.Form):
headers = ["lastname","firstname","gender","title","entity","email","company","address","phone"]
file = forms.FileField(label='CSV file',validators=[CsvFileValidator(headers)])
def clean_file(self):
file = self.cleaned_data['file']
return file
views.py
#login_required
def file_import(request):
if request.method == 'POST':
form = FileImportForm(request.POST,request.FILES)
if form.is_valid():
if request.FILES['file']:
file_post = request.FILES['file']
# Offending line below (I/O operation on closed file)
file_content = file_post.read().decode('UTF-8')
return redirect("/foo")
else:
form = FileImportForm()
return render(request,"file_import.html", { 'form': form })
How to properly process uploaded file (read, etc..)?
The error occurs because you didn't open your file properly. Here's the working way:
file_post = request.FILES['file']
f = open(file_post, "w")
As python's file operation also comes with a read-only method, you cannot do file_content = file_post.read().decode('UTF-8') directly because you didn't make this file writable.
Reference.
EDIT
As the upload file type may be incorrect, more conversions are needed. Something like:
def my_view(request):
uploaded_file = request.FILES['file']
str_text = ''
for line in uploaded_file:
str_text = str_text + line.decode() # "str_text" will be of `str` type
# do something
return something
Reference2
I am doing soapui testing, wherein i want to save request & response suffixed with todaydate.
here's my code:
// Create a File object representing the folder 'A/B'
def folder = new File( 'C:/Project/SOAPUI' )
// If it doesn't exist
if( !folder.exists() ) {
// Create all folders up-to and including B
folder.mkdirs()
}
def myOutFile = "C:/Project/SOAPUI/test_request.txt"
def request = context.expand( '${test#Request}' )
def f = new File(myOutFile)
f.write(request, "UTF-8")
=====================
I want the file name to be test_request(+today's date)
Can you suggest me some options?
Here's an option:
def myOutFile = "C:/Project/SOAPUI/test_request_${(new Date()).format('yyyy-MM-dd')}.txt"
The output looks like C:/Project/SOAPUI/test_request_2015-08-30.txt
I have very complicated problem. I´ve search whole internet and tried everything, but nothing worked. I want get string from listbox and than delete line in file with word from listbox. Can please somebody help me? Here is code:
def OnDelete(self, event):
sel = self.listbox.GetSelection()
if sel != -1:
self.listbox.Delete(sel)
subor = open("Save/savegame.txt", "r")
lines = subor.readlines()
subor.close()
subor = open("Save/savegame.txt", "w")
selstring = self.listbox.GetString(self.listbox.GetSelection())
for line in lines:
if line!=selstring:
subor.write(line)
subor.close()
And this is code for saving file:
def OnNewGame(self,event):
nameofplr = wx.GetTextFromUser('Enter your name:', 'NEW GAME')
subor=open("Save/savegame.txt","a")
subor.write( "\n" + nameofplr)
subor.close()
savegame=open("Save/" + nameofplr + ".prjct", "w+")
savegame.close()
It shows this error:
Traceback (most recent call last):
File "D:\Python\Python Projects\Project\Project.py", line 106, in OnDelete
selstring = self.listbox.GetString(self.listbox.GetSelection())
File "D:\Python\lib\site-packages\wx-3.0-msw\wx_core.py", line 12962, in GetString
return core.ItemContainer_GetString(*args, **kwargs)
wx._core.PyAssertionError: C++ assertion "IsValid(n)" failed at ....\src\msw\listbox.cpp(387) in wxListBox::GetString(): invalid index in wxListBox::GetString
Thank you very much for help!
Think about how your program works:
In the OnDelete method you check which item is selcted, then you delete this item. Then you do something with your file. After that you try to get the string from your selected item, but this was deleted by you.
You should call Delete after the line
selstring = self.listbox.GetString(self.listbox.GetSelection())
It would also be nice if you would put your code in a code block, so that we can see the indentation.
Than you very much! I have fixed it! If somebody will have the same problem you must change OnDelete code (The first code in question) for this:
def OnDelete(self, event):
sel = self.listbox.GetSelection()
f = open("Save/savegame.txt", "r")
read = f.readlines()
f.close()
name = self.listbox.GetStringSelection()
newfile = """"""
for i in read:
if name in i:
pass
else:
newfile += i
n = open("Save/savegame.txt", "w")
one = str(newfile)
n.write(one)
n.close
self.listbox.Delete(sel)