Python Append File Extension

How to add an extension to an input filename? Python Forums on Bytes. We take a look at the various ways, along with the most Pythonic way to recursively traverse through a file structure in Python 2.x and Python 3.x.

Read from an existing file, then output a file with the same name but an extension: file = rawinput ('Enter the filename: n') fileout = open ('file.out', 'w') However, when I enter a filename like 'test', it gives the output file as 'file.out' instead of 'test.out'. Here's what you want to do: Open the file that has your input in 'r'ead mode.

Computer file extension

Read the data. Close the input file.

File Extension Definition

Stackoverflow

Do some work on the data. Open a new file for output in 'w'rite mode. Write the data.

Close the output file.

This is a question regarding Unix shell scripting (any shell), but any other 'standard' scripting language solution would also be appreciated: I have a directory full of files where the filenames are hash values like this: fd73d0cf8ee68073dce270cf7e770b97 fec8047a9186fdcc98fdbfc0ea6075ee These files have different original file types such as png, zip, doc, pdf etc. Can anybody provide a script that would rename the files so they get their appropriate file extension, probably based on the output of the file command? Answer: script will work for both ouput of the filenames as well as the actual renaming.

Following csl's response: You can use file -i filename to get a MIME-type. You could potentially lookup the type in a list and then append an extension. You can find list of MIME-types and suggested file extensions on the net. I'd suggest you write a script that takes the output of file -i filename, and returns an extension (split on spaces, find the '/', look up that term in a table file) in your language of choice - a few lines at most. Then you can do something like: ls while read f; do mv '$f' '$f'.`file -i '$f' getextension.py`; done in bash, or throw that in a bash script.

Extension

File Extension Apk

Or make the getextension script bigger, but that makes it less useful next time you want the relevant extension. Edit: change from for f in. to ls while read f because the latter handles filenames with spaces in (a particular nightmare on Windows).