copy the snippet java file in middle of temp file in python - python

I am a beginner in python3
I want to copy snippet java file in the middle of other temp file which i gain the address of this file from downloading URL.
my problem is when i execute my program i have this error:
RESTART: C:/Users/user/AppData/Local/Programs/Python/Python36/refactordwon.py
the Url is:
('C:\\Users\\user\\AppData\\Local\\Temp\\tmpq5m7m_og', <http.client.HTTPMessage object at 0x0000003A854879E8>)
Traceback (most recent call last):
File "C:/Users/user/AppData/Local/Programs/Python/Python36/refactordwon.py", line 14, in <module>
file_out = open("path_file" , "r")
FileNotFoundError: [Errno 2] No such file or directory: 'path_file'
>>>
i do not know why?
because when i download the url, url shows me this address:
the Url is:
('C:\\Users\\user\\AppData\\Local\\Temp\\tmpey3yovte', <http.client.HTTPMessage object at 0x0000002233347978>)
i tried to use this address in different way but anyway i have error. i found the temp file and copied in python address.
I am sure that i have this file and the address is correct but again i have error that can not find file.
could you help me, please?!
I hope my question is clear
my code is:
import urllib.request
import os
import tempfile
#download URL
#[-------------------------
url = 'http://pages.di.unipi.it/corradini/Didattica/AP-17/PROG-ASS/03/assignment3.html'
gt_url = urllib.request.urlretrieve(url)
print("the Url is: ")
print(gt_url)
#--------------------------]
#copy sniper java file inside remote file
#[--------------------------
path_file =r'C:/Users/user/AppData/Local/Programs/Python/Python36/tmpokv2s_dw'
file_out = open("path_file" , "r")
file_in = open("snip1.java", "r")
file_out.readlines()
open("file_back", "w")
file_back.write(file_out)
pos_fileout = file_back.tell()
file_back.seek(pos_fileout)
file_back.write(file_in)
print("the content of file is: ")
file_back.close()
file_out.close()
file_in.close()
open("file_back", "r")
file_back.readlines()
print(file_back)
file_back.close()

Related

Selenium after take screenshot unlink txt file

I have some txt files in a folder, I have listed directory and garbed links. After visit links using selenium I have taken screenshot. Now I am trying do delete this link txt file.
Below code I have tried
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.keys import Keys
import os
path = "E:/xampp/htdocs/spool/"
directories = os.listdir(path)
for dir in directories:
# print(dir)
files = os.listdir(path+dir)
for file in files:
# print(path+dir+'/'+file)
f = open(path+dir+'/'+file, "r")
list = f.read()
data = list.split("||")
print(data[1])
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get(data[1])
driver.save_screenshot(data[0]+'.png')
driver.close()
os.unlink(f.name)
Problem is unlink time it's giving below error
Traceback (most recent call last):
File "index.py", line 21, in <module>
os.unlink(f.name)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'E:/xampp/htdocs/spool/7/2020-09-1112.txt'
I have also used os.close(3), After that got error "
list = f.read()
OSError: [Errno 9] Bad file descriptor
"
How can I unlink after take screenshot ?
Version python : Python 3.8.4
As u can see another process is using the txt file.
I think that's the problem here; you opened the file and didn't closed it.
I suggets you to visit https://www.tutorialspoint.com/python/file_close.htm
Try to call f.close() and then unlink.
This method of file handling is not entirely safe.
If an exception occurs when we are performing some operation with the file, the code exits with out closing the file.
In your case you forgot to close the file.
f.close()
I would recommend to use this approach to avoid such scenarios
with open("test.txt", mode= 'r', encoding = 'utf-8') as f:
# perform file operations
pass
# we dont need to explicitly close() the method, it is done internally.

my code shows error during execution while the structure is correct [duplicate]

This question already has answers here:
Why am I getting a FileNotFoundError? [duplicate]
(8 answers)
FileNotFoundError: [Errno 2] No such file or directory [duplicate]
(6 answers)
Closed 3 years ago.
i'm writing a program that write some website inside hosts file
but when i'm trying run the program it's show me an error that the directory is not found
import time
from datetime import datetime as dt
host_temp = "hosts"
host_path = r"C:\Windows\System32\drivers\etc\hosts"
redirect = "127.0.0.1"
website_list = ["www.facebook.com","www.instagram.com", "www.youtube.com"]
while True:
if dt(dt.now().year,dt.now().month,dt.now().day,20) < dt.now() < dt(dt.now().year,dt.now().month,23,1):
print("Working hours!!!")
with open(host_temp, "r+") as file:
content = file.read()
for website in website_list:
if website in content:
pass
else:
file.write(redirect + " " + website + "\n")
else:
print("Fun hours!!!")
time.sleep(5)
and this is the output
Working hours!!!
Traceback (most recent call last):
File "C:\Users\ALAA\AppData\Local\atom\app-1.38.2\hello\web site blocker\web_site_blocker.py", line 12, in <module>
with open(host_temp, "r+") as file:
FileNotFoundError: [Errno 2] No such file or directory: 'hosts'
This error has nothing to do with the structure of your program. It is just saying that it cannot find the file you say exists. You need to check the filetype of your file (you can usually see it next to your file name or in the file's properties). The majority of files have an extension.
If your file is a text file (.txt), for example, your filename would be:
host_temp = "hosts.txt"
seems like your code should be like below with full path. if you don't provide full path then python will search for 'hosts' file where your py file is stored.
with open(host_path, "r+") as file:

Download .pdf files from a webiste using python

i am trying to download all the pdfs from the webiste provided and i am using the following code:
import mechanize
from time import sleep
br = mechanize.Browser()
br.open('http://www.nerc.com/comm/CCC/Pages/AgendasHighlightsandMinutes-.aspx')
f=open("source.html","w")
f.write(br.response().read())
filetypes=[".pdf"]
myfiles=[]
for l in br.links():
for t in filetypes:
if t in str(l):
myfiles.append(l)
def downloadlink(l):
f=open(l.text,"w")
br.click_link(l)
f.write(br.response().read())
print l.text," has been downloaded"
for l in myfiles:
sleep(1)
downloadlink(l)
keep on getting the following error and can't figure out the problem why.
legal and privacy has been downloaded
Traceback (most recent call last):
File "downloads-pdfs.py", line 29, in <module>
downloadlink(l)
File "downloads-pdfs.py", line 21, in downloadlink
f=open(l.text,"w")
IOError: [Errno 13] Permission denied: u'/trademark policy'
The problem you encounter arises because you use the link URL as a filename. The character '/' is not valid in a filename. Try to modify your downloadlink function to something like this:
def downloadlink(l):
filename = l.text.split('/')[-1]
with open(filename, "w") as f:
br.click_link(l)
f.write(br.response().read())
print l.text," has been downloaded"

Python open says file doesn't exist when it does

I am trying to work out why my Python open call says a file doesn't exist when it does. If I enter the exact same file url in a browser the photo appears.
The error message I get is:
No such file or directory: 'https://yhistory.s3.amazonaws.com/media/userphotos/1_1471378042183_cdv_photo_033.jpg'
The Python code is:
full_path_filename = 'https://' + settings.AWS_STORAGE_BUCKET_NAME + '.s3.amazonaws.com/' + file_name
fd_img = open(full_path_filename, 'r')
I was wondering if this problem is something to do with the file being in an AWS S3 bucket but I am able to connect to the bucket and list its contents.
If you are trying to open a file over internet you should do something like this (assuming that you are using python 3):
import urllib.request
full_path_filename = 'https://' + settings.AWS_STORAGE_BUCKET_NAME + '.s3.amazonaws.com/' + file_name
file = urllib.request.urlopen(full_path_filename)
This will download the actual file. You can use file as an another file like object.

Send file contents over ftp python

I have this Python Script
import os
import random
import ftplib
from tkinter import Tk
# now, we will grab all Windows clipboard data, and put to var
clipboard = Tk().clipboard_get()
# print(clipboard)
# this feature will only work if a string is in the clipboard. not files.
# so if "hello, world" is copied to the clipboard, then it would work. however, if the target has copied a file or something
# then it would come back an error, and the rest of the script would come back false (therefore shutdown)
random_num = random.randrange(100, 1000, 2)
random_num_2 = random.randrange(1, 9999, 5)
filename = "capture_clip" + str(random_num) + str(random_num_2) + ".txt"
file = open(filename, 'w') # clears file, or create if not exist
file.write(clipboard) # write all contents of var "foo" to file
file.close() # close file after printing
# let's send this file over ftp
session = ftplib.FTP('ftp.example.com','ftp_user','ftp_password')
session.cwd('//logs//') # move to correct directory
f = open(filename, 'r')
session.storbinary('STOR ' + filename, f)
f.close()
session.quit()
The file will send the contents created by the Python script (under variable "filename" eg: "capture_clip5704061.txt") to my FTP Server, though the contents of the file on the local system do not equal the file on the FTP server. As you can see, I use the ftplib module. Here is my error:
Traceback (most recent call last):
File "script.py", line 33, in<module>
session.storbinary('STOR ' + filename, f)
File "C:\Users\willi\AppData\Local\Programs\Python\Python36\lib\ftplib.py", line 507, in storbinary
conn.sendall(buf)
TypeError: a bytes-like object is required, not 'str'
Your library expects the file to be open in binary mode, it appears. Try the following:
f = open(filename, 'rb')
This ensures that the data read from the file is a bytes object rather than str (for text).

Categories