How to save a path to json file as raw string - python

I want to save a path to json file, code as below:
def writeToJasonFile(results, filename):
with open(os.path.join(filename), "w") as fp:
try:
fp.write(json.dumps(results))
except Exception as e:
raise Exception("Exception while writing results " % e)
if __name__ == '__main__':
file_path = os.getcwd()
writeToJasonFile(file_path, 'test.json')
When I open json file, the string is saved as escape str: "C:\\test\\Python Script"
How could I dump it as raw string? Saying "C:\test\Python Script"

I could do it in another way. I replace '\' with '/' for the path string and then save it. Windows is able to open the location with this format "C:/test/Python Script". If someone has the answer for the original question, please post here.

Related

Function returns 'None' after reading file data, (only after FileNotFoundError exception is handled)

I am a total beginner to Python, and am attempting the following exercise:
1) Write code to open and read a file
2) Allow the user to specify a filename
3) Add error handling to allow the user to try again if the file cannot be located
I have tried searching for any related questions prior to this but was unable to resolve the issue below:
import sys
def file_name():
file_name = input("Please choose a filename you wish to open/read: ")
return file_name
def file_reader(file_name):
try:
while file_name.find(".") < 0:
file_name += ".txt"
read_mode = "r"
with open(file_name, read_mode) as file:
output = "\n" + file.read() + "\n"
return output
except FileNotFoundError:
print("\nFILE NOT FOUND! Please try again.\n")
print_contents()
except:
error = sys.exc_info()[0]
print("Many apologies! Something has went wrong!")
print(error)
def print_contents():
print(file_reader(file_name()))
while True:
print_contents()
Here, the function "file_reader(file_name)" concatenates ".txt" to the end of the user-specified filename where there is no file extension already specified, then attempts to read from the file.
In the event of a FileNotFoundError exception, this then prompts the user for another input.
However, if the user then enters a valid filename after the exception, the file contents are returned, followed by 'None'.
I am very confused as to why 'None' is returned with the file contents ONLY ONCE after a FileNotFoundError exception has been handled, after which the 'while True' loop seems to work correctly again. How can I prevent 'None from being returned with the user-specified file data after a FileNotFoundError exception was previously handled?
As I am still very new to Python, any other constructive feedback is welcomed.

Parsing XML from websites and save the code?

I would like to parse the xml code from a website like
http://ops.epo.org/3.1/rest-services/published-data/publication/docdb/EP1000000/biblio
and save it in another xml or csv file.
I tried it with this:
import urllib.request
web_data = urllib.request.urlopen("http://ops.epo.org/3.1/rest-services/published-data/publication/docdb/EP1000000/biblio")
str_data = web_data.read()
try:
f = open("file.xml", "w")
f.write(str(str_data))
print("SUCCESS")
except:
print("ERROR")
But in the saved XML data is between every element '\n' and at the beginning ' b' '
How can i save the XML data without all the 'n\' and ' b' '?
If you write the xml file in binary mode, you don't need to convert the data read into a string of characters first. Also, if you process the data a line at a time, that should get rid of '\n' problem. The logic of your code could also be structured a little better IMO, as shown below:
import urllib.request
web_data = urllib.request.urlopen("http://ops.epo.org/3.1/rest-services"
"/published-data/publication"
"/docdb/EP1000000/biblio")
data = web_data.read()
with open("file.xml", "wb") as f:
for line in data:
try:
f.write(data)
except Exception as exc:
print('ERROR')
print(str(exc))
break
else:
print('SUCCESS')
read() returns data as bytes but you can save data without converting to str(). You have to open file in byte mode - "wb" - and write data.
import urllib.request
web_data = urllib.request.urlopen("http://ops.epo.org/3.1/rest-services/published-data/publication/docdb/EP1000000/biblio")
data = web_data.read()
try:
f = open("file.xml", "wb")
f.write(data)
print("SUCCESS")
except:
print("ERROR")
BTW: To convert bytes to string/unicode you have to use ie. decode('utf-8') .
If you use str() then Python uses own method to create string and it adds b" to inform you that you have bytes in your data.

Write files to disk with python 3.x

Using BottlePy, I use the following code to upload a file and write it to disk :
upload = request.files.get('upload')
raw = upload.file.read()
filename = upload.filename
with open(filename, 'w') as f:
f.write(raw)
return "You uploaded %s (%d bytes)." % (filename, len(raw))
It returns the proper amount of bytes every single time.
The upload works fine for file like .txt, .php, .css ...
But it results in a corrupted file for other files like .jpg, .png, .pdf, .xls ...
I tried to change the open() function
with open(filename, 'wb') as f:
It returns the following error:
TypeError('must be bytes or buffer, not str',)
I guess its an issue related to binary files ?
Is there something to install on top of Python to run upload for any file type ?
Update
Just to be sure, as pointed out by #thkang I tried to code this using the dev version of bottlepy and the built-in method .save()
upload = request.files.get('upload')
upload.save(upload.filename)
It returns the exact same Exception error
TypeError('must be bytes or buffer, not str',)
Update 2
Here the final code which "works" (and dont pop the error TypeError('must be bytes or buffer, not str',)
upload = request.files.get('upload')
raw = upload.file.read().encode()
filename = upload.filename
with open(filename, 'wb') as f:
f.write(raw)
Unfortunately, the result is the same : every .txt file works fine, but other files like .jpg, .pdf ... are corrupted
I've also noticed that those file (the corrupted one) have a larger size than the orginal (before upload)
This binary thing must be the issue with Python 3x
Note :
I use python 3.1.3
I use BottlePy 0.11.6 (raw bottle.py file, no 2to3 on it or anything)
Try this:
upload = request.files.get('upload')
with open(upload.file, "rb") as f1:
raw = f1.read()
filename = upload.filename
with open(filename, 'wb') as f:
f.write(raw)
return "You uploaded %s (%d bytes)." % (filename, len(raw))
Update
Try value:
# Get a cgi.FieldStorage object
upload = request.files.get('upload')
# Get the data
raw = upload.value;
# Write to file
filename = upload.filename
with open(filename, 'wb') as f:
f.write(raw)
return "You uploaded %s (%d bytes)." % (filename, len(raw))
Update 2
See this thread, it seems to do same as what you are trying...
# Test if the file was uploaded
if fileitem.filename:
# strip leading path from file name to avoid directory traversal attacks
fn = os.path.basename(fileitem.filename)
open('files/' + fn, 'wb').write(fileitem.file.read())
message = 'The file "' + fn + '" was uploaded successfully'
else:
message = 'No file was uploaded'
In Python 3x all strings are now unicode, so you need to convert the read() function used in this file upload code.
The read() function returns a unicode string aswell, which you can convert into proper bytes via encode() function
Use the code contained in my first question, and replace the line
raw = upload.file.read()
with
raw = upload.file.read().encode('ISO-8859-1')
That's all ;)
Further reading : http://python3porting.com/problems.html

display an error message when file is empty - proper way?

hi im slowly trying to learn the correct way to write python code. suppose i have a text file which i want to check if empty, what i want to happen is that the program immediately terminates and the console window displays an error message if indeed empty. so far what ive done is written below. please teach me the proper method on how one ought to handle this case:
import os
def main():
f1name = 'f1.txt'
f1Cont = open(f1name,'r')
if not f1Cont:
print '%s is an empty file' %f1name
os.system ('pause')
#other code
if __name__ == '__main__':
main()
There is no need to open() the file, just use os.stat().
>>> #create an empty file
>>> f=open('testfile','w')
>>> f.close()
>>> #open the empty file in read mode to prove that it doesn't raise IOError
>>> f=open('testfile','r')
>>> f.close()
>>> #get the size of the file
>>> import os
>>> import stat
>>> os.stat('testfile')[stat.ST_SIZE]
0L
>>>
The pythonic way to do this is:
try:
f = open(f1name, 'r')
except IOError as e:
# you can print the error here, e.g.
print(str(e))
Maybe a duplicate of this.
From the original answer:
import os
if (os.stat(f1name).st_size == 0)
print 'File is empty!'
If file open succeeds the value of 'f1Cont` will be a file object and will not be False (even if the file is empty).One way you can check if the file is empty (after a successful open) is :
if f1Cont.readlines():
print 'File is not empty'
else:
print 'File is empty'
Assuming you are going to read the file if it has data in it, I'd recommend opening it in append-update mode and seeing if the file position is zero. If so, there's no data in the file. Otherwise, we can read it.
with open("filename", "a+") as f:
if f.tell():
f.seek(0)
for line in f: # read the file
print line.rstrip()
else:
print "no data in file"
one can create a custom exception and handle that using a try and except block as below
class ContentNotFoundError(Exception):
pass
with open('your_filename','r') as f:
try:
content=f.read()
if not content:
raise ContentNotFoundError()
except ContentNotFoundError:
print("the file you are trying to open has no contents in it")
else:
print("content found")
print(content)
This code will print the content of the file given if found otherwise will print the message
the file you are trying to open has no contents in it

python mp3 meta-tag

I try to write a script than scan recursive a given directory and if found mp3 get and just print meta tag for it. What ever I passed to getEyeD3Tag I got an exception. Here is my code that i have written so far
def getEyeD3Tags(path):
try:
trackInfo = eyeD3.Mp3AudioFile(path)
tag = trackInfo.getTag()
tag.link(path)
print tag.getArtist()
print tag.getAlbum()
print tag.getTitle()
#return (tag.getArtist(),tag.getTitle(),tag.getAlbum())
except eyeD3.InvalidAudioFormatException:
print "File %s is not a mp3 file " % path
mp3Num=0
temp=os.walk(valid-folder-name)
for root, dirs, files in temp:
for i in files:
if os.path.join(root,i):
temp=os.path.splitext(i)
temp[1].lower()
if temp[1]=='.mp3':
mp3Path=os.path.join(root,i)
print mp3Path
getEyeD3Tags(mp3Path)
mp3Num+=1
raw_input()
#print "**"
else:
print "Error invalid path"
print "\n\n"
#raw_input()
print mp3Num
raw_input()
And BTW is it a way to get genre of mp3 file using eyeD3?
Thx in advance
To check if the file being parsed is a valid mp3, call the eyeD3.isMp3File(filename) method.
The following is from a short script I made to auto-sort my music folder.
def parseIDETag(self, path):
if eyeD3.isMp3File(path):
That way, if the file isn't an mp3, it'll just skip over it.
Also, str(tag.getGenre()) returns the genre as a string using eyeD3.

Categories

Resources