how to get filename given FileData object in Python? - python-3.x

I have a FileData object file, where when I print(file) I will get:
<FileData ID_0a0eebac2.dcm (ID_0a0eebac2.dcm)>
I am hoping to extract the name of the file, "ID_0a0eebac2.dcm", from this object. How can I do this?

This way you can do it
In python the name is an attribute of IOWrapper : 'https://docs.python.org/3/library/io.html'
file = open('ID_0a0eebac2.dcm')
#to get the name of the file you can do this
file_name = file.name # the name of the file is saved as an attribute of the object
If you want to make a function
def get_file_name(file):
return file.name
I hope you got your answer

Related

How to Convert tdms file to text or csv in python

Here i tried nptdms module but giving error
tdms_file = TdmsFile.as_dataframe('file.tdms',time_index=False, absolute_time=False, scaled_data=True)
AttributeError: 'str' object has no attribute 'groups'
please anyone have idea to convert tdms file csv or text file ,
here i don't know what is inside the file
You need to use the filepath and read in the actual file. Right now you are trying to read in the string 'file.tdms' which is merely 9 letters -- so you get the 'str' object error. Find the actual filepath for the file.tdms and you should be fine. It could look something like this:
filepath = '/home/x/y/file.tdms'
tdms_file = TdmsFile.as_dataframe(filepath,time_index=False, absolute_time=False, scaled_data=True)

Python Pillow library not saving files with same name in same location

Below is the code I am using to convert a binary data into image and then saving it
img = base64.b64decode(rec.image3)
img_conv = Image.open(io.BytesIO(img))
img_format = img_conv.format
img_conv.save('{}/{}'.format(path, rec.image_name), format(img_format))
There are 4 images with same code and I want to handle the scenario where if all the file names are same in the same location, it should force to save the 4 images even though it has duplicate name.
Any suggestion would be appreciated. Thanks.
Supposing that you want to keep each file under a different name: Append '_' to the original filename as long as a file with such a name exists in your directory.
from pathlib import Path
path_to_save = Path(path, rec.image_name)
while path_to_save.exists():
path_to_save = Path(str(path_to_save) + '_')
img_conv.save(path_to_save, format(img_format))

Converting multiple files in a directory into .txt format. But file names become Binary

So I am creating plagiarism software, for that, I need to convert .pdf, .docx,[enter image description here][1] etc files into a .txt format. I successfully found a way to convert all the files in one directory to another. BUT the problem is, this method is changing the file names
into binary values. I need to get the original file name which I am gonna need in the next phase.
**Code:**
import os
import uuid
import textract
source_directory = os.path.join(os.getcwd(), "C:/Users/syedm/Desktop/Study/FOUNDplag/Plagiarism-checker-Python/mainfolder")
for filename in os.listdir(source_directory):
file, extension = os.path.splitext(filename)
unique_filename = str(uuid.uuid4()) + extension
os.rename(os.path.join(source_directory, filename), os.path.join(source_directory, unique_filename))
training_directory = os.path.join(os.getcwd(), "C:/Users/syedm/Desktop/Study/FOUNDplag/Plagiarism-checker-Python/trainingdata")
for process_file in os.listdir(source_directory):
file, extension = os.path.splitext(process_file)
# We create a new text file name by concatenating the .txt extension to file UUID
dest_file_path = file + '.txt'
# extract text from the file
content = textract.process(os.path.join(source_directory, process_file))
# We create and open the new and we prepare to write the Binary Data which is represented by the wb - Write Binary
write_text_file = open(os.path.join(training_directory, dest_file_path), "wb")
# write the content and close the newly created file
write_text_file.write(content)
write_text_file.close()
remove this line where you rename the files:
os.rename(os.path.join(source_directory, filename), os.path.join(source_directory, unique_filename))
that's also not binary, but a uuid instead.
Cheers

How can I pass a excel/csv file as a function parameter?

How can I pass a excel/csv file as a function parameter?
I have wrote a piece of code to copy content from one excel file to another excel file. Now I want to define it as a function so I just have to mention file name from which I want to transfer data to my existing file.
Thanks a lot in advance.
I am very new to Python Programming, and looking forward to learn a lot.
def feed_input_file(InputFile):
InputFile = "D:\\Python_Projects\\ABC.xlsx" #(I am passing Input file at the moment but I don't wanna pass it here)
#( Here I am trying to call my function parameter value)
Workbook1 = xl.load_workbook(feed_input_file(InputFile))
............
Still not quite sure what you are trying to do but if you want to create a function that will take a filename as an argument you could try something along the lines of:
def processFile(fn:str):
#Reads in the contents of file specified by fn
content = ''
with open(fn, 'a') as f:
data = f.read()
#Do something with data here to create content
return content
Then in your main part of the script
for filename in listofFiles:
fle_out = processFile(filename
#Do something here with file contents

object has no attribute error when trying to read from a file

Im trying to code something that replaces a string in a file with input from the user. I keep getting the error builtins.AttributeError: 'str' object has no attribute 'read' What is causing this error? As far as I know the syntax should be correct. I'm still pretty new to Python though.
My code is:
import os
filename = input('Enter a filename: ')
old = input('Enter the old string to be replaced: ')
new = input('Enter the new string to replace the old string: ')
os.path.isfile(filename)
data = ''
open(filename, 'r')
data += filename.read().replace(old, new)
filename.close()
open(filename, 'w')
filename.write(data)
filename.close()
print('Done')
You need a file handler. You can't use read method directly on filename.
For e.g
fh = open(filename, 'r')
data = fh.readlines()

Resources