How do I write to a website/HTML Document using python 3? - python

I'm using python 3 and I was able to read the code from my html document but I was unable to write to it. How would I go about this. I'll show you what I mean:
import urllib.request
locator=urllib.request.urlopen("file:///E:/Programming/Calculator.html", "r")
transfer=locator.read()
print("\n\n",transfer, "\n")
locator.close()
locator=urllib.request.urlopen("file:///E:/Programming/Calculator.html","w+")
locator.write("<p> Hello this site has been slightly changed</p>")
locator.close()
locator=urllib.request.urlopen("file:///E:/Programming/Calculator.html","r")
new=locator.read()
print(new)
locator.close()
So I'm to read to it but i can't write to it or change any of it's code. Why is this?
Also, I tried to read from an actual url website using the exact same code as above but replacing the url and removing the write function. The interpreter came up with an error, and I wasn't able to read from the site. How can I read from a website too?
Note: I'm just learning, I'm not actually gonna do anything illegal I just want to become more knowledgeable with this kind of stuff
Also if I change write to append() it still produces an error
import urllib.request
locator=urllib.request.urlopen("file:///E:/Programming/Calculator.html", "r")
transfer=locator.read()
print("\n\n",transfer, "\n")
locator.close()
locator=urllib.request.urlopen("file:///E:/Programming/Calculator.html", "w+")
with open("file:///E:/Programming/Calculator.html") as f:
f.write('something')
locator.close()
The above is a piece of code suggested by another member ut instead of writing to the url it up with an error saying:
Traceback (most recent call last):
File "C:\Users\KENNY\Desktop\Python\practice.py", line 10, in <module>
with open("file:///E:/Programming/Calculator.html") as f:
OSError: [Errno 22] Invalid argument: 'file:///E:/Programming/Calculator.html'
Ignore the spacing its just the way i pasted it. all the code should be in line up to the with open part where the f.write function is idented

urllib.request.urlopen returns a file-like object.
These objects expose a read method, but should not allow you to write.
I like to think of it as, when using urllib it is like requesting the file as you would if you typed the resource into your browser. You can't write to it. You request it and it is served to you.
If you want to open the file for writing you can use the open method
with open('E:/Programming/Calculator.html', 'w+') as f:
f.write('something')
The above example uses with statement which is basically a shortcut for manually closing the file when the code exits the with block.
It is similar to
f = open('E:/Programming/Calculator.html', 'w+')
f.write('something')
f.close()
#Lattyware posted a great tutorial on it, many more can be found online. The pep outlines what it is for.
It seems like you might be confusing urlopen and the open command.

Related

Download xml-file and save it to a text file

I'm very new at programming and have a problem. I need to create a Python function that uses the request external module to download an XML-file, and then saves the text of the response to a text file.
So far i've tried this:
import requests
def downloading_xml():
r = requests.get('https://www.w3schools.com/xml/simplexsl.xml')
print(r.text)
But I don't get it quite right. I think my main problem is the last part, I don't know how to save the text of the response to a text file. Any ideas? Thanks in advance!
Here you go. If you want to know more about Python file operations follow this link
Python I/O
import requests
def downloading_xml():
r = requests.get('https://www.w3schools.com/xml/simplexsl.xml')
print(r.text)
with open("filename.txt", "w+") as f:
f.write(r.text)
f.close()
Now call the function
downloading_xml()
To save to a text file you can do something like this:
textfile=open("anyname.xml",'w')
textfile.write(r.text)
textfile.close()
you may need to include the path to the file as well

My function is not calling properly after I close a file?

I am in an intro class and I've been looking for an answer for hours but I can't find one. My assignment is to use a txt. file and the list in it as an address book and whenever I call my menu() function after closing the file it doesn't run right it just is blank, I've printed "H" in places throughout the program to find where the logic error is and I've singled it down to after I close the file on line 47, If anybody would be able to help me it would be greatly appreciated and I'm a noob so roast my code as much as you like.my code
How are you opening the file right now? You may be opening the file in a write mode that overwrites prior content, if so I would suggest using open in the following form:
with open("demofile.txt", "r") as file:
# Do things with file such as reading the lines
lines = file.readlines()
...
This way the file will be open in read-only mode
Your code while open the file may throw some error and thus ending the try statement. Try using with statement or raise the error on except to track where's the error.

Python Win 32 error while trying to rename a file

I have a folder with several csv-files in it. I have to change the filename of every file with a string that I find in the file. So I tried the script below. It looks like it is working until I try to rename the file.
What did I try:
First I didn't have the file.close() line in the program, but did didn't fix the problem
I added a line print(file.closed) to see if the file was actually closed
I tried to get the os.rename out of the indented 'with' block. But I keep getting the same error
I tried to get the os.rename out of any block. But then I get a Winerror 123, where it sais that the filename , directoryname etc. is incorrect.
I also read the questions WindowsError 32 while trying to os.rename and Windows Error: 32 when trying to rename file in python.
I understood that maybe I had to close the file with f.close since this is the handler, but that didn't work as well.
The code that I tried:
for f in glob.glob("/path/*.csv"):
with open(f, "r") as file:
#read the lines in the csv-file
data = file.read()
#search the lines that have been read for a pattern and save that in "search"
search = re.findall("some_pattern", data)
#The result was a list. With this line I tried to change it into a string
file.close()
Listtostring = ''.join([str(elem) for elem in search])
#I only want to use a part of the match in the new file name
name = Listtostring.replace("part_of_string", "")
os.rename(f,f+name)
I hope somebody can give me some tips and explain what I am doing wrong. Pretty new to Python, so if you can give me some insight in my mistakes, than it's appreciated!
Thank you for your comments and time. It seemed that one of the files that was opened was still busy in some process and therefore the code didn’t work. I first closed all the applications that were running, but that didn’t work. After that I restarted the computer and the script worked fine!

Program running but file not opening using open() function

I am just learning about file manipulation and created a simple 'text.txt' file. This file, as well as my source code('files.py') share the same parent directory('files/'). I am trying to open the file:
import os
helloFile = open('./text.txt')
However, when I run this at the command line no error is thrown but no file is opened. It seems like it is running with no problem but not doing what I want it to do. Anyone know why?
Well, you should probably read() from file as you only created file descriptor object which targets the file, but didn't really do any operation on it.
also, I recommend you to use
with open('./text.txt') as f:
helloFile = f.read()
it will automatically close file for you,
in other case you need to close file manually like below:
f = open('./text.txt')
helloFile = f.read()
f.close()

Parsing a .lis file in Python

I am trying to parse in a .lis file into python to perform further analysis on the data but every time I get the following error,
<_io.TextIOWrapper name='Data.lis' mode='r' encoding='cp1252'>
I am parsing in the file with the standard command,
open(fileName)
Is there a certain package I need to install or is my parsing method incorrect?
What you got as an output doesn't appear to be an error, it is just telling you that python opened the file, and you have a file type object now.
Further, the operation you performed only got you part of the way. When reading a file, you need to:
Open the file
Store it as a variable (usually)
Read the variable a line at a time
Parse the result of your reading
Close the file
I usually start by trying to open the file in a program like Notepad++. That way I can get an idea of what I am trying to parse.
Let's walk through an example:
filename = 'myfile.lis'
with open(filename) as f:
for line in f:
print(line)
The code above opens the .lis file, and then prints the file to the console one line at a time. The with statement ensure that the file gets closed after we're done.
However, you could just as well replace the print() command with a parse() command of your own choosing:
def parse(input_line):
if 'text' in input_line:
print('I found \'text\' in line \'{}\''.format(input_line))
Hopefully that will get you started. If you are able to provide more detail about what the contents of your .lis file is, or what you are looking to extract from that file, I'm sure many around here can provide better guidance.

Categories

Resources