Saving a file with python - python-3.x

I'm trying to save the input from the user to a file new or overwrite the existing one with the same name but the error is saying "No such file or directory"
user_save is suppose to be an input with all files in the path he wat to save the file to
file_name name of the file where to save it
import os
user_input = input('Введите строку: ')
user_save = input('Куда хотите сохранить документ? Введите последовательность папок (через пробел)\n')
user_save = 'C\\' + user_save.replace(' ', '\\')
file_name = input('Введите имя файла: ')
file_name = file_name + '.txt'
if os.path.exists(os.path.join(user_save, file_name)):
overwrite = input('Вы действительно хотите перезаписать файл?').lower()
if overwrite == 'нет':
print('Программа не сохранена')
elif overwrite == 'да':
with open(os.path.join(user_save, file_name),'w') as file:
file.write(user_input)
file.close()
print('Файл успешно перезаписан!')
else:
with open(os.path.join(user_save, file_name)) as file:
file.write(user_input)
file.close()
print('Файл успешно перезаписан!')

Related

How to find and replace string in a file using input of line number in python

My requirement is to find a file from a directory and then in that file find LOG_X_PARAMS and in that append a string after the first comma this is what i am having for now
import os, fnmatch
def findReplacelist(directory, finds, new_string, file):
line_number = 0
list_of_results = []
for path, dirs, files in os.walk(os.path.abspath(directory)):
if file in files:
filepath = os.path.join(path, file)
with open(filepath, 'r') as f:
for line in f:
line_number += 1
if finds in line:
list_of_results.append((line_number))
print(list_of_results)
def get_git_root(path):
Path = "E:\Code\modules"
file_list=["pb_sa_ch.c"]
for i in file_list:
findReplacelist(Path , "LOG_1_PARAMS", "instance", i)
The example line is below change
LOG_X_PARAMS(string 1, string 2); #string1 andd string2 is random
this to
LOG_X_PARAMS(string 1, new_string, string 2);
I can find the line number using LOG_X_PARAMS now using this line number I need to append a string in the same line can someone help solving it ?
This is how I would do the task. I would find the files I want to change, read then file line by line and if there is a change in the file, then write the file back out. Heres the approach:
def findReplacelist(directory, finds, new_string, file):
for path, dirs, files in os.walk(os.path.abspath(directory)):
if file in files:
filepath = os.path.join(path, file)
find_replace(finds, new_string, filepath)
def find_replace(tgt_phrase, new_string, file):
outfile = ''
chgflg = False
with open(file, 'r') as f:
for line in f:
if tgt_phrase in line:
outfile += line + new_string
chgflg = True
else:
outfile += line
if chgflg:
with open(file, 'w') as f:
f.write(outfile)

user input forget to key in the file name or accidentally press enter without break the program

I don't want this script to be close or end if the user forget to insert the file extension or wrong file name or accidentally press enter without key in the file name. How can I do it?
def sum_usage():
file_name = []
print('\tMake sure the file is on the same directory with this script!')
while True:
file_name = input('\tEnter file name with file extension (.xlsx): ')
if file_name == file_name:
print('\n')
print(file_name)
df = pd.read_excel(file_name, index_col = 0)
print(tabulate(df, headers = ['Access SSID', 'Radio Frequencies', 'User Count', 'Total Traffic'], tablefmt = 'psql'))
break
else:
print('There is no file name. Please enter correct file name.')
Something wrong here but I'm not sure:
file_name = input('\tEnter file name with file extension (.xlsx): ')
if file_name == file_name:
print('\n')
print(file_name)
df = pd.read_excel(file_name, index_col = 0)
print(tabulate(df, headers = ['Access SSID', 'Radio Frequencies', 'User Count', 'Total Traffic'], tablefmt = 'psql'))
You need to check if the file_name is empty.
Example:
def sum_usage():
file_name = []
print('\tMake sure the file is on the same directory with this script!')
while True:
file_name = input('\tEnter file name with file extension (.xlsx): ')
if file_name.strip() != '':
print('\n')
print(file_name)
df = pd.read_excel(file_name, index_col = 0)
print(tabulate(df, headers = ['Access SSID', 'Radio Frequencies', 'User Count', 'Total Traffic'], tablefmt = 'psql'))
break
else:
print('There is no file name. Please enter correct file name.')
Yes, I have found a solution to my own question.
while True:
file_name = input('\tEnter file name: ')
if os.path.exists(file_name): # I add this statement to check if the file exist or not.
with open(file_name) as df:
print('\n')
print(file_name)
df = pd.read_excel(file_name, index_col = 0)
print(tabulate(df, headers = ['Access SSID', 'Radio Frequencies', 'User Count', 'Total Traffic'], tablefmt = 'psql'))
break
else:
print('\tMake sure you enter correct file name with the file extension')

How to change the files extension using python

In a Folder, I have 100 files with extensions '.txt','.doc','.pdf'. I need to rename the files as:
If the filename ends with '.txt' -> replace filename ends with '.jpg'
If the filename ends with '.doc' -> replace filename ends with '.mp3'
If the filename ends with '.pdf' -> replace filename ends with '.mp4'
I have tried this one so far
import os,sys
folder ="C:/Users/TestFolder"
for filename in os.listdir(folder):
base_file, ext = os.path.splitext(filename)
print(ext)
if ext == '.txt':
print("------")
print(filename)
print(base_file)
print(ext)
os.rename(filename, base_file + '.jpg')
elif ext == '.doc':
print("------")
os.rename(filename, base_file + '.mp3')
elif ext == '.pdf':
print("------")
os.rename(filename, base_file + '.mp4')
else:
print("Not found")
To begin with , you can store your mappings in a dictionary, then when you are iterating over your folder, and you find the extension, just use the mapping to make the new file name and save it.
import os
folder ="C:/Users/TestFolder"
#Dictionary for extension mappings
rename_dict = {'txt': 'jpg', 'doc': 'mp3', 'pdf': 'mp4'}
for filename in os.listdir(folder):
#Get the extension and remove . from it
base_file, ext = os.path.splitext(filename)
ext = ext.replace('.','')
#If you find the extension to rename
if ext in rename_dict:
#Create the new file name
new_ext = rename_dict[ext]
new_file = base_file + '.' + new_ext
#Create the full old and new path
old_path = os.path.join(folder, filename)
new_path = os.path.join(folder, new_file)
#Rename the file
os.rename(old_path, new_path)

Python: os.walk usage for scanning specified directory and search specified file issue

I want to scan current and deeper folder to search specified file.
[~/test]$tree -a
Upon is my test environment.
[~/test]$ls
NCRAM955E/ RNCMST954E/ RNCMST957E/ test.py*
Below is my code:
import os, shutil, sys, getopt, re
def GetOption(argv):
FileDir = ""
Roptarget = ""
Dirtarget=[]
try:
opts, args = getopt.getopt(argv, "hD:F:",["FileDir=", "Roptarget="])
except getopt.GetoptError:
print ('Error arg input -D <FileDir> -F <Roptarget>')
sys.exit(2)
for opt, arg in opts:
if opt == "-h":
print ('Error arg input -D <FileDir> -F <Roptarget>')
sys.exit()
elif opt in ("-D", "--FileDir"):
FileDir = arg
Dirtarget = FileDir.split("|")
elif opt in ("-F", "--Roptarget"):
Roptarget = arg
return(Dirtarget, Roptarget)
#Below self defined function need update
def detect_walk(file_dir):
L_0 = []
L = []
DirList,Ropfile = GetOption(sys.argv[1:])
print("DirList = " + str(DirList))
print("Ropfile = " + Ropfile)
for root, dirs, files in os.walk(file_dir):
for file in files:
L_0.append(file)
if " ".join(L_0).find(Ropfile):
print("target rop file = " + Ropfile)
L.append(os.path.join(root, Ropfile))
return(L)
if __name__ == '__main__':
file_path = "/home/test/"
List = detect_walk(file_path)
My expect output, for exapmle
if I type python test.py -D "RNCRAM955E|RNCMST954E" -F "^A20180520.1300+0300-1315+0300*RNCMST954E_statsfile.xml$"
the program will only search foler RNCRAM955E and RNCMST954E, when specified file match pattern found , it will display the full-path of the target file.
i am python freshers. please give me some advice. thank you.
I have update my code, this code will enable transform specified file which in specified folder to another folder.
Use like python temp.py -D "RNCMST954E|RNCMST957E|RNCRAM955E" -F "A20180520\.13*", but some codes remain improve, as you see, the filename after -F should add escape symbol \ . So, how can I improve this ?
import os, shutil, sys, getopt, re
def GetOption(argv):
FileDir = ""
Roptarget = ""
Dirtarget=[]
try:
opts, args = getopt.getopt(argv, "hD:F:",["FileDir=", "Roptarget="])
except getopt.GetoptError:
print ('Error arg input -D <FileDir> -F <Roptarget>')
sys.exit(2)
for opt, arg in opts:
if opt == "-h":
print ('Error arg input -D <FileDir> -F <Roptarget>')
sys.exit()
elif opt in ("-D", "--FileDir"):
FileDir = arg
Dirtarget = FileDir.split("|")
elif opt in ("-F", "--Roptarget"):
Roptarget = arg
return(Dirtarget, Roptarget)
def detect_walk(file_dir):
L = []
desdir = "/home/ekoopgj/ITK/Task/test_folder/"
for root, dirs, files in os.walk(file_dir):
for file in files:
if re.search(fileIndex,file) is not None:
L.append(os.path.join(root, file))
print("start copy " + os.path.join(root, file) + " to " + desdir)
shutil.copyfile(os.path.join(root, file),desdir + file)
if __name__ == '__main__':
DirList,fileIndex = GetOption(sys.argv[1:])
#use LOOP For and store the file_path varibale as a Formal parameters , can reduce the search time if the target folder contains too many files.
for dir in DirList:
file_path = "/home/ekoopgj/ITK/Task/0521/"
file_path += dir
print("dir = " + dir)
List = detect_walk(file_path)

Archive/pack a directory with contents as plain-text representation?

Under Linux / bash, how can I obtain a plain-text representation of a directory of its contents? (Note that by "plain-text" here I mean "UTF-8").
In other words, how could I "pack" or "archive" a directory (with contents - including binary files) as a plain text file - such that I could "unpack" it later, and obtain the same directory with its contents?
I was interested in this for a while, and I think I finally managed to cook up a script that works in both Python 2.7 and 3.4 -- however, I'd still like to know if there is something else that does the same. Here it is as a Gist (with some more comments):
https://gist.github.com/anonymous/1a68bf2c9134fd5312219c8f68713632
Otherwise, I'm posting a slightly abridged version here (below) for reference.
The usage is: to archive/pack into a .json text file:
python archdir2text-json.py -a /tmp > myarchdir.json
... and to unpack from the .json text file into the current (calling) directory:
python archdir2text-json.py -u myarchdir.json
Binary files are handled as base64.
Here is the script:
archdir2text-json.py
#!/usr/bin/env python
import pprint, inspect
import argparse
import os
import stat
import errno
import base64
import codecs
class SmartDescriptionFormatter(argparse.RawDescriptionHelpFormatter):
def _fill_text(self, text, width, indent):
if text.startswith('R|'):
paragraphs = text[2:].splitlines()
rebroken = [argparse._textwrap.wrap(tpar, width) for tpar in paragraphs]
rebrokenstr = []
for tlinearr in rebroken:
if (len(tlinearr) == 0):
rebrokenstr.append("")
else:
for tlinepiece in tlinearr:
rebrokenstr.append(tlinepiece)
return '\n'.join(rebrokenstr)
return argparse.RawDescriptionHelpFormatter._fill_text(self, text, width, indent)
textchars = bytearray({7,8,9,10,12,13,27} | set(range(0x20, 0x100)) - {0x7f})
is_binary_string = lambda bytes: bool(bytes.translate(None, textchars))
cwd = os.getcwd()
if os.name == 'nt':
import win32api, win32con
def folder_is_hidden(p):
if os.name== 'nt':
attribute = win32api.GetFileAttributes(p)
return attribute & (win32con.FILE_ATTRIBUTE_HIDDEN | win32con.FILE_ATTRIBUTE_SYSTEM)
else:
return os.path.basename(p).startswith('.') #linux-osx
def path_hierarchy(path):
hierarchy = {
'type': 'folder',
'name': os.path.basename(path),
'path': path,
}
try:
cleared_contents = [contents
for contents in os.listdir(path)
if not(
os.path.isdir(os.path.join(path, contents))
and
folder_is_hidden(os.path.join(path, contents))
)]
hierarchy['children'] = [
path_hierarchy(os.path.join(path, contents))
for contents in cleared_contents
]
except OSError as e:
if e.errno == errno.ENOTDIR:
hierarchy['type'] = 'file'
else:
hierarchy['type'] += " " + str(e)
if hierarchy['type'] == 'file':
isfifo = stat.S_ISFIFO(os.stat(hierarchy['path']).st_mode)
if isfifo:
ftype = "fifo"
else:
try:
data = open(hierarchy['path'], 'rb').read()
ftype = "bin" if is_binary_string(data) else "txt"
if (ftype == "txt"):
hierarchy['content'] = data.decode("utf-8")
else:
hierarchy['content'] = base64.b64encode(data).decode("utf-8")
except Exception as e:
ftype = str(e)
hierarchy['ftype'] = ftype
return hierarchy
def recurse_unpack(inobj, relpath=""):
if (inobj['type'] == "folder"):
rpname = relpath + inobj['name']
sys.stderr.write("folder name: " + rpname + os.linesep);
os.mkdir(rpname)
for tchild in inobj['children']:
recurse_unpack(tchild, relpath=relpath+inobj['name']+os.sep)
elif (inobj['type'] == "file"):
rfname = relpath + inobj['name']
sys.stderr.write("file name: " + rfname + os.linesep)
if inobj['ftype'] == "txt":
with codecs.open(rfname, "w", "utf-8") as text_file:
text_file.write(inobj['content'])
elif inobj['ftype'] == "bin":
with open(rfname, "wb") as bin_file:
bin_file.write(base64.b64decode(inobj['content']))
if __name__ == '__main__':
import json
import sys
parser = argparse.ArgumentParser(formatter_class=SmartDescriptionFormatter, description="""R|Command-line App that packs/archives (and vice-versa) a directory to a plain-text .json file; should work w/ both Python 2.7 and 3.4
see full help text in https://gist.github.com/anonymous/1a68bf2c9134fd5312219c8f68713632""")
parser.add_argument('input_paths', type=str, nargs='*', default=['.'],
help='Paths to files/directories to include in the archive; or path to .json archive file')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-a', '--archive', action='store_true', help="Interpret input_paths as paths to files/directories, and archive them to a .json file (output to stdout)")
group.add_argument('-u', '--unpack', action='store_true', help="Interpret input_paths as path to an archive .json file, and unpack it in the current directory")
args = parser.parse_args()
if (args.archive):
valid_input_paths = []
for p in args.input_paths:
if os.path.isdir(p) or os.path.exists(p):
valid_input_paths.append(p)
else:
sys.stderr.write("Ignoring invalid input path: " + p + os.linesep)
sys.stderr.write("Encoding input path(s): " + str(valid_input_paths) + os.linesep)
path_hier_arr = [path_hierarchy(vp) for vp in valid_input_paths]
outjson = json.dumps(path_hier_arr, indent=2, sort_keys=True, separators=(',', ': '))
print(outjson)
elif (args.unpack):
valid_input_paths = []
for p in args.input_paths:
if os.path.isdir(p) or os.path.exists(p):
valid_input_paths.append(p)
else:
sys.stderr.write("Ignoring invalid input path: " + p + os.linesep)
for vp in valid_input_paths:
with open(vp) as data_file:
data = json.load(data_file)
for datachunk in data:
recurse_unpack(datachunk)

Resources