create file containing '/' in file name in python - python-2.7

how can I create a file in python if the filename contains '/'
url='https://www.udacity.com/cs101x/index.html'
f=open(url,'w')
f.write('123')
f.close()
above code produces an error as
Traceback (most recent call last):
File "9.py", line 2, in <module>
f=open(url,'w')
IOError: [Errno 22] invalid mode ('w') or filename:https://www.udacity.com/cs101x/index.html'

Use os.path.basename() to isolate the filename.
import os
url='https://www.udacity.com/cs101x/index.html'
filename = os.path.basename(url)
f=open(filename,'w')
f.write('123')
f.close()
This will create a file called index.html

Related

Read attribute data from an xml in python

I am trying to read data from an xml file from an url using request module in python
import requests
from requests.auth import HTTPBasicAuth
import xml.etree.ElementTree as et
url ="https://sample.com/simple.xml"
response = requests.get(url,auth=HTTPBasicAuth(username,password))
xml_data = et.fromstring(response.text)
The error I am getting is:
Traceback (most recent call last):
File "C:\Python27\myfolder\Artifactory.py", line 156, in <module>
xml_data = et.fromstring(xml_response.text)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 1311, in XML
parser.feed(text)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 1657, in feed
self._parser.Parse(data, 0)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xae' in position 8419: ordinal not in range(128)
So i changed the code to xml_data = et.parse(response.text)
then the error is :
Traceback (most recent call last):
File "C:\Python27\myfolder\Artifactory.py", line 156, in <module>
xml_data = et.parse(xml_response.text)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 1182, in parse
tree.parse(source, parser)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 647, in parse
source = open(source, "rb")
IOError: [Errno 2] No such file or directory: u'<?xml version="1.0" encoding="utf-8"?>
After this error the xml data is getting printed
please help me in this issue
et.parse requires file path (not contents).
You need to encode response to utf-8
xml_data = et.fromstring(response.text.encode('utf-8'))
The first attempt seems like an encoding issue with python.
try adding this to your code between your last import and your url variable.
import sys
reload(sys)
sys.setdefaultencoding("utf8")

Error with creating a csv file in python: Operation not permitted

I am trying to create an empty csv file in python (2.7) but see the following error. Can anyone tell me why this is happening?
>>> tutorial_out = open('tutorial.csv', 'wb')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 1] Operation not permitted: 'tutorial.csv'
This is a permission issue, you probably don't have permission to write in that directory.
Solution: Modify permission of that directory or run as root.

Python 2.7 file read error

I am struggling with file access - I have my python 2.7 here:
C:\Python27
I created a txt file data.txt
and I am trying to get the shell to read and print values from it. Location of data.txt is in the same folder (C:\Python27\data.txt)
Every time I got the same error msg:
Traceback (most recent call last):
File "C:/Python27/FileReader.py", line 1, in <module>
infile = open('data.txt', 'r') # Open the file for reading.
IOError: [Errno 2] No such file or directory: 'data'
You need to enter the full filename data.txt instead of data only:
infile = open('data.txt', 'r')

When i tried to rename a txt file in pythonwin

I wrote a script to rename a txt file in pythonwin as below.
import os
os.rename("northrdge.txt","northrdgechg.txt")
the above text file is in the path:C:\Users\gmayil\Desktop\northrdge.txt.
after this when i run the script i met below error:
Can anyone please help me on this ?
Traceback (most recent call last):
File "C:\Python27\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 433, in ImportFile
exec codeObj in __main__.__dict__
File "<auto import>", line 1, in <module>
File "C:\Python27\Tools\gopi\renamefile.py", line 2, in <module>
os.rename("northrdge.txt","northrdgechg.txt")
WindowsError: [Error 2] The system cannot find the file specified
Your python-file lies in "C:\Python27\Tools\gopi\renamefile.py", but you say your txt-file is in "C:\Users\gmayil\Desktop\". If you pass a relative path, python searches in its own directory, which is "C:\Python27\Tools\gopi\".
So all you have to do is giving the complete path:
os.rename("C:\Users\gmayil\Desktop\northrdge.txt", "C:\Users\gmayil\Desktop\northrdgechg.txt")

Unable to copy files of certain extension in Python using loop

I want to loop through the files present in Audio_files folder and check if it is raw file or wave file and put it in the respective directories.
Here is my code:
import shutil
import os
source = os.listdir("/home/GM/codec_implement/Audio_files/")
destination = "/home/GM/codec_implement/raw_files/"
destination2 = "/home/GM/codec_implement/raw_files/wave_files/"
for files in source:
if files.endswith(".wav"):
shutil.copy(files,destination)
elif files.endswith(".raw"):
shutil.copy(files,destination)
else:
print "Invalid format"
Please let me know where I am making mistake. Error i get is:
Traceback (most recent call last): File "./checkaudiofiles.py", line
12, in shutil.copy(files,destination) File
"/usr/lib/python2.7/shutil.py", line 119, in copy copyfile(src, dst)
File "/usr/lib/python2.7/shutil.py", line 82, in copyfile with
open(src, 'rb') as fsrc: IOError: [Errno 2] No such file or directory:
'test_sound.wav'
The error means that the test_sound.wav file is not on that directory. These file might be removed between the two proces or the os.listdir() and the shutil.copy() don't list the files the same way.