I have this code portion for instance :
fichiers=glob.glob('/path/*.file')
for f in fichiers:
if os.path.isfile(f):
fichier = open(f,'r')
for l in fichier:
m = regex.match(l)
if m:
print('%s/ EMO /%s'%(m.group(1),m.group(3)))
#here I want to write this modified line
else:
#write line non modified
fichier.close()
And I would like, instead of printing results in the shell, apply the substitution to all lines of each line with copying files with new names or in a new directory (to be sure not making mistakes).
Have you some idea to teach me how to do that please ?
It's really quite simple: all you need to do is define your output directory and open a new file in that directory to write to, every time you open a file that you read. Check this out:
import glob
import os
outdirpath = "/path/to/output/directory"
for fpath in glob.glob('/path/*.file'):
if not os.path.isfile(fpath): continue
with open(fpath) as fichier, open(os.path.join(outdirpath, os.path.basename(fpath)), 'w') as outfile:
for line in fichier:
m = regex.match(line)
if m:
outfile.write('%s/ EMO /%s'%(m.group(1),m.group(3)))
else:
outfile.write(line)
Related
I'm using this code to load the ECG-ID database into MATLAB:
%% Initialization
clear all; close all; clc
%% read files from folder A
% Specify the folder where the files live.
myFolder = 'Databases\ECG_ID';
% Check to make sure that folder actually exists. Warn user if it doesn't.
if ~isfolder(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s\nPlease specify a new folder.', myFolder;)
uiwait(warndlg(errorMessage);)
myFolder = uigetdir(; % Ask for a new one.)
if myFolder == 0
% User clicked Cancel
return;
end
end
% Get a list of all files in the folder with the desired file name pattern.
filePattern = fullfile(myFolder, '**/rec_*'; % Change to whatever pattern you need.)
theFiles = dir(filePattern;)
for k = 1 : length(theFiles)
baseFileName = theFiles(k.name;)
fullFileName = fullfile(theFiles(k.folder, baseFileName);)
fprintf(1, 'Now reading %s\n', fullFileName;)
% Now do whatever you want with this file name,
% such as reading it in as an image array with imread()
[sig, Fs, tm] = rdsamp(fullFileName, [1],[],[],[],1;)
end
But I keep getting this error message:
Now reading C:\Users\******\Documents\MATLAB\Databases\ECG_ID\Person_01\rec_1.atr
Error using rdsamp (line 203)
Could not find record: C:\Users\******\Documents\MATLAB\Databases\ECG_ID\Person_01\rec_1.atr. Search path is set to: '.
C:\Users\******\Documents\MATLAB\mcode\..\database\ http://physionet.org/physiobank/database/'
I can successfully load one signal at a time (but I can't load the entire database using the above code) using this command:
[sig, Fs, tm] = rdsamp('Databases\ECG_ID\Person_01\rec_1');
How do I solve this problem? How can I load all the files in MATLAB?
Thanks in advance.
Can someone fix the below python code please?
I intend to open writable files to dump something in each of these file later (that code is not here) with the following names,
aaa2021-02-02.rpt
bbb2021-02-02.rpt
ccc2021-02-02.rpt
My code starts here:
f_name = list()
with open("files_names") as f :
lines = f.readlines()
lines = [x.strip() for x in lines]
for line in lines:
f_name.append(line)
for m in range(len(f_name)):
f_name[m] = open("f_name[m]{}.rpt".format(date.today()), "w+")
#content of the file, files_names:
#aaa
#bbb
#ccc
i have this function: write_reversed_file(input_filename, output_filename) that writes to the given output file the contents of the given input file with the lines in reversed order. i just need the output to be written to the file (output_filename) rather than to the terminal (python shell).
the only part im missing is to store the output into the file.
i successfully managed to complete the reversing lines part.
def write_reversed_file(input_filename, output_filename):
for line in reversed(list(open(filename))):
print(line.rstrip())
def write_reversed_file(input_filename, output_filename):
s = ""
f = open(input_filename,"r")
lines = f.read().split("\n")
f.close()
for line in reversed(lines):
s+=line.rstrip()+"\n"
f = open(outPutFile.txt,"w")
f.write(s)
f.close()
It is good practice to use 'with open as' format when working with files since it is automatically closing the file for us. (as recommended in docs.python.org)
def write_reversed_file(input_filename, output_filename):
with open(output_filename, 'w') as f:
with open(input_filename, 'r') as r:
for line in reversed(list(r.read())):
f.write(line)
write_reversed_file("inputfile.txt", "outputfile.txt")
How can I get Python to loop through a directory and find a specific string in each file located within that directory, then output a summary of what it found?
I want to search the long files for the following string:
FIRMWARE_VERSION = "2.15"
Only, the firmware version can be different in each file. So I want the log file to report back with whatever version it finds.
import glob
import os
print("The following list contains the firmware version of each server.\n")
os.chdir( "LOGS\\" )
for file in glob.glob('*.log'):
with open(file) as f:
contents = f.read()
if 'FIRMWARE_VERSION = "' in contents:
print (file + " = ???)
I was thinking I could use something like the following to return the extra characters but it's not working.
file[:+5]
I want the output to look something like this:
server1.web.com = FIRMWARE_VERSION = "2.16"
server2.web.com = FIRMWARE_VERSION = "3.01"
server3.web.com = FIRMWARE_VERSION = "1.26"
server4.web.com = FIRMWARE_VERSION = "4.1"
server5.web.com = FIRMWARE_VERSION = "3.50"
Any suggestions on how I can do this?
You can use regex for grub the text :
import re
for file in glob.glob('*.log'):
with open(file) as f:
contents = f.read()
if 'FIRMWARE_VERSION = "' in contents:
print (file + '='+ re.search(r'FIRMWARE_VERSION ="([\d.]+)"',contents).group(1))
In this case re.search will do the job! with searching the file content based on the following pattern :
r'FIRMWARE_VERSION ="([\d.]+)"'
that find a float number between two double quote!also you can use the following that match anything right after FIRMWARE_VERSIONbetween two double quote.
r'FIRMWARE_VERSION =(".*")'
This is my Python Program that I have been having some issues with:
-- coding: cp1252 --
from time import gmtime, strftime
print("Welcome to the PiggyBank version 1.")
num_write = int(input("How much money would you like to store in your PiggyBank?"))
f = open("PiggyBanks_Records.txt", "w")
current_time = strftime("%Y-%m-%d %H:%M:%S", gmtime())
convert_1 = str(current_time)
convert_2 = str(int(num_write))
add_1 = ("\n" + convert_1 + " £" + convert_2)
add_2 = ("\n" + add_1) #Tried to make it so new line is added every time the program is run
final_record = str(add_2)
print("Final file written to the PiggyBank: " + final_record)
#Write to File
f.write(final_record)
f.close()
Right now whenever the program writes to the file it over-writes. I would preferably would like to keep, like a history of the amounts added. If anyone can help so the string that needs to be written to the .txt file goes down by one line and essentially keeps going for ever. I am also open to any suggestion on how I can shorten this code.
You need to open your file with append mode :
f = open("PiggyBanks_Records.txt", "a")
Using the 'w' write option with open automatically looks for the specified file, and deletes its contents if it already exists (which you can read about here) or creates it if it doesn't. Use 'a' instead to add / append to the file.