I have the following code to get messages from group:
getmessage = client.get_messages(dialog, limit=1000)
for message in getmessage:
try:
if message.media == None:
print("message")
continue
else:
print("Media**********")
client.download_media(message)
The code above write the media.
I need to know the file name/file type before I write the file, How can I get it?
You can use a filename of your choosing to ensure that said filename will be used:
filename = 'some-file'
filename = client.download_media(message, filename)
Then filename will be some-file with the correct extension.
Otherwise, Telethon will generate a file name for the file (it will try the original name, and if it exists, append (n) to avoid overwriting existing files), so you can't really know where it will be saved beforehand (but the method does return the final filename).
Related
Code below is connecting to my FTPserver and looks for file; these files have timestamps at start of name and added filename, like 'timestamp+name.txt'. Those timestamps usually have 16 characters, look below:
I'm trying to make this "searcher" to search files by ignoring timestamps, so it should look for 'FTPtest.txt' actually. I'm struggling with for loop usage. I did little code to test:
files = ftp.nlst()
for x in files:
print(x[16:])
This indeed lists files with cutted names but I dont know how to make use of it in my code. This code below is fully working and doing it's job, but now I need to modify it. In input user writes only short filename ('FTPtest.txt') and not full name, but it searches for exact input, ignoring timestamps. Here are just always 16 characters in timestamp, but the name can be different than FTPtest.txt. Below is my code:
from ftplib import FTP
from ftplib import FTP, error_perm
def repeat():
ftp = FTP(host="ip")
ftp.login(user='user', passwd='pass')
file_name = str(input('>>> What is name of your file? \n'))
try:
ftp.cwd('/test')
if file_name in ftp.nlst():
print("+++File found!+++")
else:
print("---File not found---")
except error_perm:
print("File does not exist")
ftp.quit()
while True:
repeat()
My understanding is that you just want to see if there is a exact match by file excluding the first 16 characters so doing something like.
try:
ftp.cwd('/test')
if file_name in [f[16:] for f inftp.nlst()]:
print("+++File found!+++")
else:
print("---File not found---")
except error_perm:
print("File does not exist")
Should work. Note this is not the most efficient as it iterates twice over the list but it is concise.
I am trying to upload a file in to a folder in the box using the below code:
folder_id = '22222'
new_file = client.folder(folder_id).upload('/home/me/document.pdf')
print('File "{0}" uploaded to Box with file ID {1}'.format(new_file.name, new_file.id))
This code is not replacing the existing document.pdf in the box folder, rather it is keeping the older version of the file. I would like to remove the file in the target and keep the latest file. How to achieve this?
Since your goal is to replace the original file, you can try to overwrite its existing content. Here is an example. You will need to check for the filename if it is already present in the BOX folder though
folder_id = '22222'
file_path = '/home/me/document.pdf'
results = client.search().query(query='document', limit=1, ancestor_folder_ids=[folder_id], type='file', file_extensions=['pdf'])
file_id = None
for item in results:
file_id = item.id
if file_id:
updated_file = client.file(file_id).update_contents(file_path)
print('File "{0}" has been updated'.format(updated_file.name))
else:
new_file = client.folder(folder_id).upload(file_path)
print('File "{0}" uploaded to Box with file ID {1}'.format(new_file.name, new_file.id))
Its not replacing it because every time you upload new file it assign it a new id so the old file will never be replaced.
This is what I found in official docs.
Try to give it a name and then try that.
upload[source]
Upload a file to the folder. The contents are taken from the given file path, and it will have the given name. If file_name is not specified, the uploaded file will take its name from file_path.
Parameters:
file_path (unicode) – The file path of the file to upload to Box.
file_name (unicode) – The name to give the file on Box. If None, then use the leaf name of file_path
preflight_check (bool) – If specified, preflight check will be performed before actually uploading the file.
preflight_expected_size (int) – The size of the file to be uploaded in bytes, which is used for preflight check. The default value is ‘0’, which means the file size is unknown.
upload_using_accelerator (bool) –
If specified, the upload will try to use Box Accelerator to speed up the uploads for big files. It will make an extra API call before the actual upload to get the Accelerator upload url, and then make a POST request to that url instead of the default Box upload url. It falls back to normal upload endpoint, if cannot get the Accelerator upload url.
Please notice that this is a premium feature, which might not be available to your app.
Returns:
The newly uploaded file.
Return type:
File
I have a Flask view that generates data and saves it as a CSV file with Pandas, then displays the data. A second view serves the generated file. I want to remove the file after it is downloaded. My current code raises a permission error, maybe because after_request deletes the file before it is served with send_from_directory. How can I delete a file after serving it?
def process_data(data)
tempname = str(uuid4()) + '.csv'
data['text'].to_csv('samo/static/temp/{}'.format(tempname))
return file
#projects.route('/getcsv/<file>')
def getcsv(file):
#after_this_request
def cleanup(response):
os.remove('samo/static/temp/' + file)
return response
return send_from_directory(directory=cwd + '/samo/static/temp/', filename=file, as_attachment=True)
after_request runs after the view returns but before the response is sent. Sending a file may use a streaming response; if you delete it before it's read fully you can run into errors.
This is mostly an issue on Windows, other platforms can mark a file deleted and keep it around until it not being accessed. However, it may still be useful to only delete the file once you're sure it's been sent, regardless of platform.
Read the file into memory and serve it, so that's it's not being read when you delete it later. In case the file is too big to read into memory, use a generator to serve it then delete it.
#app.route('/download_and_remove/<filename>')
def download_and_remove(filename):
path = os.path.join(current_app.instance_path, filename)
def generate():
with open(path) as f:
yield from f
os.remove(path)
r = current_app.response_class(generate(), mimetype='text/csv')
r.headers.set('Content-Disposition', 'attachment', filename='data.csv')
return r
In my code, user uploads file which is saved on server and read using the server path. I'm trying to delete the file from that path after I'm done reading it. But it gives me following error instead:
An error occurred while reading file. [WinError 32] The process cannot access the file because it is being used by another process
I'm reading file using with, and I've tried f.close() and also f.closed but its the same error every time.
This is my code:
f = open(filePath)
with f:
line = f.readline().strip()
tempLst = line.split(fileSeparator)
if(len(lstHeader) != len(tempLst)):
headerErrorMsg = "invalid headers"
hjsonObj["Line No."] = 1
hjsonObj["Error Detail"] = headerErrorMsg
data['lstErrorData'].append(hjsonObj)
data["status"] = True
f.closed
return data
f.closed
after this code I call the remove function:
os.remove(filePath)
Edit: using with open(filePath) as f: and then trying to remove the file gives the same error.
Instead of:
f.closed
You need to say:
f.close()
closed is just a boolean property on the file object to indicate if the file is actually closed.
close() is method on the file object that actually closes the file.
Side note: attempting a file delete after closing a file handle is not 100% reliable. The file might still be getting scanned by the virus scanner or indexer. Or some other system hook is holding on to the file reference, etc... If the delete fails, wait a second and try again.
Use below code:
import os
os.startfile('your_file.py')
To delete after completion:
os.remove('your_file.py')
This
import os
path = 'path/to/file'
with open(path) as f:
for l in f:
print l,
os.remove(path)
should work, with statement will automatically close the file after the nested block of code
if it fails, File could be in use by some external factor. you can use Redo pattern.
while True:
try:
os.remove(path)
break
except:
time.sleep(1)
There is probably an application that is opening the file; check and close the application before executing your code:
os.remove(file_path)
Delete files that are not used by another application.
I'm new to python and the following piece of code is driving me crazy. It lists the files in a directory and for each file does some stuff. I get a IOError: [Errno2] No such file or directory: my_file_that_is_actually_there!
def loadFile(aFile):
f_gz = gzip.open(aFile, 'rb')
data = f_gz.read()
#do some stuff...
f_gz.close()
return data
def main():
inputFolder = '../myFolder/'
for aFile in os.listdir(inputFolder):
data = loadFile(aFile)
#do some more stuff
The file exists and it's not corrupted. I do not understand how it's possible that python first finds the file when it checks the content of myFolder, and then it cannot find itanymore... This happens on the second iteration of my for loop only with any files.
NOTE: Why does this exception happen ONLY at the second iteration of the loop?? The first file in the folder is found and opened without any issues...
This is because open receives the local name (returned from os.listdir). It doesn't know that you mean that it should look in ../myFolder. So it receives a relative path and applies it to the current dir. To fix it, try:
data = loadFile(os.path.join(inputFolder, aFile))