replacing line in a document with Python [duplicate] - python

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))

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.

printing all the ".lnk" filenames in foldes and sub folders [duplicate]

This question already has answers here:
Extract file name from path, no matter what the os/path format
(22 answers)
Closed 2 years ago.
so there are alot of files with .lnk extension in the start menu folder C:\ProgramData\Microsoft\Windows\Start Menu\Programs i want to print all those file names so i tried this code:
import os
import glob
startmenu = r'C:\ProgramData\Microsoft\Windows\Start Menu\Programs'
os.chdir(startmenu)
for file in glob.glob("**/*.lnk", recursive = True):
print(file)
it prints the link to the files, but i want to print only the file names with the extension of ".lnk"
Convert the absolute path to list then take the last element from the list. See the below code.
import os
import glob
startmenu = r'C:\ProgramData\Microsoft\Windows\Start Menu\Programs'
os.chdir(startmenu)
for file in glob.glob("**/*.lnk", recursive=True):
print(os.path.split(file)[-1])

Import File from File Directory (Python) [duplicate]

This question already has answers here:
import module from string variable
(7 answers)
How can I import a module dynamically given the full path?
(35 answers)
Closed 3 years ago.
Currently, I have the directory to a file
"../Model.py"
This model has a class called Test.
Using the string of the directory, I want to import and use the class Test.
How do I do so?
(The String will change dynamically)
From: https://docs.python.org/3/tutorial/modules.html#the-module-search-path
I tested this and I believe it should work for you as well. The code should look as follows:
import sys
directory = '../Model.py'
directory = directory[:-8]
sys.path.append(directory)
from Model import Test

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

How to change file extension with Python? [duplicate]

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

Categories