I am trying to upload a file to an ftp server with python using the ftplib.
This is what i have:
def ftp(cmd):
cmd = cmd.split(' ')
try: cmd[3]
except: return 'host user password file (ftpdir)'
try: session = ftplib.FTP(cmd[0],cmd[1],cmd[2])
except: return 'wrong credentials/host'
try: file = open(cmd[3], 'rb')
except: return 'unable to reach file'
try: cmd[4]
except: pass
else:
if cmd[4] !='':
ftplib.FTP.cwd(ftpdir)
name = file.split('\\')[-1]
session.storbinary('STOR ' + name, file) # send the file
file.close() # close file and FTP
session.quit()
I give the function a command in the form of 'host user password file ftpdir' where ftpdir is not required. The error I get is this one:
Traceback (most recent call last):
...some lines of referring...
File "C:\somedir\somefile.py", line 155, in ftp
file = open(cmd[3],'rb')
TypeError: open() takes exactly 1 argument (2 given)
If i try the command "file = open(cmd[3], 'rb')" with a given 'cmd' as entry in a python shell it works fine.
This question is now answered. The problem was that I defined another function open(arg) which took exactely one argument. After changing the name of that function, everything worked fine.
Thank you for your time everyone who read this.
Related
I am making a file open function for the beginning of my program where it prompts the user to input a filename and then it will open that file. I was trying to use the try-except function for this so that if it's a valid file then print it and if its not a valid file to return a filenotfound error. I'm unsure how I can implement the file not found error. This is what I came up with so far:
def open_file():
file = input("Please input a file to use: ")
try:
fp = open(file)
except:
filenotfounderror
I'm pretty sure this should work but I'm not sure what to write in place of the filenotfound error after except
This is how it should be:
def open_file():
file = input("Please input a file to use: ")
try:
fp = open(file)
except FileNotFoundError:
print("File Not Found")
I think the below is what you are looking for
def open_file():
file_name = input("Please input a file to use: ")
try:
fp = open(file_name)
# do something with the file - dont forget to close it
except FileNotFoundError:
print(f"Wrong file or file path: {file_name}")
You don't need try/except for this; Python will raise a FileNotFoundError without your help if the file cannot be found.
What your code would do is replace every other error (permission denied, invalid file name, wrong moon phase over Redmond, etc) with FileNotFoundError. Don't do that (and generally don't use a blanket except, at least until you know exactly what you are doing).
If you want to raise an exception, the keyword for that is raise. For example;
try:
with open(input("File: ")) as inp:
# ... do something
except FileNotFoundError as exc:
print("ooops, we got a", exc)
raise ValueError("Surreptitiously replacing %s" % exc)
def EDIT():
print("\nEnter the file you want to edit")
command = input('\n$input<<')
try:
f = open(command + ".txt", "a")
f.write(input('\n$append<<'))
except FileNotFoundError:
print('\nSorry, there was an error while trying to create your file. The file doesn\'t exist.\n')
finally:
NOTEPAD()
Whenever I try to run this specific line of code, the program runs, but when going to check on the file, nothing changes
You need to close the file to flush the buffer.
It's usually best to use a context manager so the file will be closed automatically.
def EDIT():
print("\nEnter the file you want to edit")
command = input('\n$input<<')
try:
with open(command + ".txt", "a") as f:
f.write(input('\n$append<<'))
except FileNotFoundError:
print('\nSorry, there was an error while trying to create your file. The file doesn\'t exist.\n')
finally:
NOTEPAD()
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.
so I have a problem trying to run this python code as administrator so I am not able to access and write on host file. Can anyone help me? I have looked through many of other questions but non of them seem to work.
Host File Directory: C:\Windows\System32\Drivers\etc\hosts
(Such as)
Request UAC elevation from within a Python script?
Some of these answers actually work on prompting to get administrator access, but it still doesn't give permission to my program. The only way I figured out is to run python shell as administrator first and then run the code or run the command prompt as administrator and open python file with command prompt.
WEBSITE
https://boostlog.io/#faisalnad/create-a-website-blocker-with-python-5afe86ff47018500491f4898
This program is made for blocking website.
import time
from datetime import datetime as dt
# change hosts path according to your OS
hosts_path = r”C:\Windows\System32\Drivers\etc\hosts”
# localhost's IP
redirect = "127.0.0.1"
# websites That you want to block
website_list = ["www.facebook.com","facebook.com",
"dub119.mail.live.com","www.dub119.mail.live.com",
"www.gmail.com","gmail.com"]
while True:
# time of your work
if dt(dt.now().year, dt.now().month, dt.now().day,8) < dt.now() < dt(dt.now().year, dt.now().month, dt.now().day,16):
print("Working hours...")
with open(hosts_path, 'r+') as file:
content = file.read()
for website in website_list:
if website in content:
pass
else:
# mapping hostnames to your localhost IP address
file.write(redirect + " " + website + "\n")
else:
with open(hosts_path, 'r+') as file:
content=file.readlines()
file.seek(0)
for line in content:
if not any(website in line for website in website_list):
file.write(line)
# removing hostnmes from host file
file.truncate()
print("Fun hours...")
time.sleep(5)
This is the error:
Working hours...
Traceback (most recent call last):
File "C:\Users\Key\Desktop\random project.py", line 19, in <module>
with open(hosts_path, 'r+') as file:
PermissionError: [Errno 13] Permission denied: 'C:\\Windows\\System32\\Drivers\\etc\\hosts'
FILE DIRECTORY
You can add write permission for the user under which your program runs following this link to add permission to the host file
This question already has answers here:
Python: prevent mixed tabs/spaces on module import
(1 answer)
Indentation Error in Python [duplicate]
(7 answers)
Closed 5 years ago.
The following code is confusing the mess out of me. I've got a zip file which I am opening in a context manager. I'm trying to extract the contents of this zip file to a temporary directory. However, when I execute this code block, it tells me that there was an "Attempt to read ZIP archive that was already closed". I find this very strange, as the zip file in question was opened in (with?) a context manager! I've inserted several print statements for calls to methods/properties associated with the object at hand. They return successfully.
Where have I gone wrong? Why does the file believe itself closed?
Any help would be appreciated!
(Edit) Please find the traceback below.
Also, is there a better way to check if a zipfile is in fact open? Other than checking if .fp is True/False?
if config.get('settings', 'new_quarter') == "Yes":
#This gets the latest zip file, by year and quarter
new_statements_path = os.path.join(config.get('cleaning', 'historic_dir'), 'sql_files')
for directory,dirnames, filenames in os.walk(new_statements_path):
zips = [f for f in filenames if ".zip" in f]
highest_quarter = max([z.split('Q')[1].split('.')[0] for z in zips])
print 'Targeting this quarter for initial tables: %s' % (highest_quarter)
for z in zips:
if 'sql_files' in f:
if z.split('Q')[1].split('.')[0] == highest_quarter:
with zipfile.ZipFile(os.path.join(directory,z), 'r') as zip_f:
print zip_f.fp
initial_tables = tempfile.mkdtemp()
print 'initial tables', initial_tables, os.path.exists(initial_tables)
#Ensure the file is read/write by the creator only
saved_umask = os.umask(0077)
try:
print zip_f.namelist()
print zip_f.fp
zip_f.printdir()
zip_f.extractall(path=initial_tables)
except:
print traceback.format_exc()
os.umask(saved_umask)
if os.path.exists(initial_tables) == True:
shutil.rmtree(initial_tables)
Traceback:
Traceback (most recent call last):
File "/Users/n/GitHub/s/s/s/extract/extract.py", line 60, in extract_process
zip_f.extractall(path=initial_tables)
File "/Users/n/anaconda/lib/python2.7/zipfile.py", line 1043, in extractall
self.extract(zipinfo, path, pwd)
File "/Users/n/anaconda/lib/python2.7/zipfile.py", line 1031, in extract
return self._extract_member(member, path, pwd)
File "/Users/n/anaconda/lib/python2.7/zipfile.py", line 1085, in _extract_member
with self.open(member, pwd=pwd) as source, \
File "/Users/n/anaconda/lib/python2.7/zipfile.py", line 946, in open
"Attempt to read ZIP archive that was already closed"
RuntimeError: Attempt to read ZIP archive that was already closed
(SECOND EDIT)
Here's the (reasonably) minimal & complete version. In this case, the code runs fine. Which makes sense, there's nothing fancy going on. What's interesting is I placed the full example (the one below) immediately above the previous example (above). The code below still executes just fine, but the code above still produces the same error. The only difference however is the new_statements_path variable. In the code above, this string comes from a config file. Surely, this isn't the root of the error. But I can't see any other differences.
import traceback
import os
import zipfile
import tempfile
import shutil
new_statements_path = '/Users/n/Official/sql_files'
for directory,dirnames, filenames in os.walk(new_statements_path):
zips = [f for f in filenames if ".zip" in f]
highest_quarter = max([z.split('Q')[1].split('.')[0] for z in zips])
print 'Targeting this Quarter for initial tables: %s' % (highest_quarter)
for z in zips:
if 'sql_files' in f:
if z.split('Q')[1].split('.')[0] == highest_quarter:
with zipfile.ZipFile(os.path.join(directory,z), 'r') as zip_f:
print zip_f.fp
initial_tables = tempfile.mkdtemp()
print 'initial tables', initial_tables, os.path.exists(initial_tables)
#Ensure the file is read/write by the creator only
saved_umask = os.umask(0077)
try:
print zip_f.namelist()
print zip_f.fp
zip_f.printdir()
zip_f.extractall(path=initial_tables)
except:
print traceback.format_exc()
os.umask(saved_umask)
if os.path.exists(initial_tables) == True:
shutil.rmtree(initial_tables)
if os.path.exists(initial_tables) == True:
shutil.rmtree(initial_tables)