How to change file extension with Python? [duplicate] - python

This question already has answers here:
Extracting extension from filename in Python
(33 answers)
Closed 7 years ago.
I'm trying to make a program that will take a file, say my_test_file.log and make a new file called my_test_file.mdn. I'd like to be able to use this program by typing python renameprogram.py my_test_file.log into the command line. The original file will always end in .log.

from shutil import copyfile
from glob import glob
map(lambda x:copyfile(x,x[:-3]+"mdn"),glob("*.log"))
or perhaps more simply
...
import sys
copyfile(sys.argv[1],sys.argv[1][:-3]+"mdn")

You certainly can create a Python program that will accomplish this, but there are shell level commands that already do this.
For Linux/Unix:
mv my_test_file.log my_test_file.mdn
For Windows (see this link):
rename my_test_file.log my_test_file.mdn

Related

How do I move a text file to a different folder? [duplicate]

This question already has answers here:
How to move a file in Python?
(11 answers)
Closed 2 years ago.
I already know how to create and write a text file in Python, but how do I move that file to a different folder on my system?
You can either make a system call with os.system:
import os
os.system("mv /path/to/file /path/to/destination")
or rename it:
os.rename("/path/to/file", "/path/to/destination")
or move it with `shutil.move`:
```python
import shutil
shutil.move("/path/to/file", "/path/to/destination")
First solution works only in bash shells, second and third should be portable over all platforms. Third has the advantage that you can specify a folder as destination, the file will then be put into that folder with the same name as in the old location.

How to call a function if the function's file name is known and is a string? [duplicate]

This question already has answers here:
How can I import a module dynamically given its name as string?
(10 answers)
Closed 7 years ago.
I am scanning a directory for new python scripts.
I expect each script file to have an arbitrary function report().
Say, the following files were found in my directory: ['file1.py', 'file2.py'].
So "file1.py" should contain:
def report():
print('I am just a script.')
I need to call report() function for each one of them.
How to do it?
You can use the builtin function __import__ to do a dynamic import, something like this:
for file in files:
mod = __import__(file)
mod.report()
Note - you will need to strip the '.py' extension from the filename, and this will be made more complicated if the current working directory is not on the python path.
This SO answer has some more detail on __import__(): Dynamic module import in Python. If you need to load from somewhere off the python path, then look at the second answer

replacing line in a document with Python [duplicate]

This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Closed 8 years ago.
I have the following file and I would like to replace #sys.path.insert(0, os.path.abspath('.'))
with sys.path.extend(['path1', 'path2'])
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
However, the following code does not change the line.
with open(os.path.join(conf_py_path, "conf.py"), 'r+') as cnfpy:
for line in cnfpy:
line.replace("#sys.path.insert(0, os.path.abspath('.')))",
"sys.path.extend(%s)\n" %src_paths)
cnfpy.write(line)
How is it possible to replace the line?
Try fileinput to change a string in-place within a file:
import fileinput
for line in fileinput.input(filename, inplace=True):
print(line.replace(string_to_replace, new_string))

How to find what files are in a folder [duplicate]

This question already has answers here:
Directory-tree listing in Python
(21 answers)
Closed 9 years ago.
I am writing a function that is recieving a folder path as an arguemnt. I want her to add into a dictionary what's inside the folder (like dir in CMD)
How can I do this ?
Thank you in advance,
Iliya
import os
print os.listdir('/tmp')
Similar Topics:
Directory listing in Python
Also, I use os.path and glob a lot while manipulating file system path.
You might want to check it out.

How do I list contents of a tar file without extracting it in python? [duplicate]

This question already has answers here:
reading tar file contents without untarring it, in python script
(4 answers)
Closed 2 years ago.
I've got a huge *.tar.gz file and I want to see the list of files contained in it without extracting the contents (preferably with mtimes per file). How can I achieve that in python?
You can use TarFile.getnames() like this:
#!/usr/bin/env python3
import tarfile
tarf = tarfile.open('foo.tar.gz', 'r:gz')
print(tarf.getnames())
http://docs.python.org/3.3/library/tarfile.html#tarfile.TarFile.getnames
And if you want mtime values you can use getmembers().
print([(member.name, member.mtime) for member in tarf.getmembers()])

Categories