How to edit a specific line in a text file using Pascal - freepascal

I am struggling to replace a specific line of text with my text from my program. So far, all I have is opening the file for editing...I tried searching on the internet but the closest one I could find was this: http://wiki.freepascal.org/File_Handling_In_Pascal. The page has everything about appending new texts under a line in an existing file and creating an entirely new file for adding texts into, but not for a specific line in an existing file...
var musicfile: TextFile;
AssignFile(musicfile, 'AlbumList.dat');
Append(musicfile);
WriteLn(musicfile, 'A text a want to replace line 5 with, but I dont know how to find line 5...');
Close(musicfile);

You can create new file and copy all the lines except the one you want to replace. Like this:
var musicfile: TextFile;
newfile: TextFile;
line: string[100]; // long enough to hold the longest line in the file
i: word; // counter for the lines
AssignFile(musicfile, 'AlbumList.dat');
AssignFile(newfile, 'AlbumList(1).dat'); // create new file
Reset(musicfile);
Rewrite(newfile); // open the new file for writing
i := 0 // we are at the 1st (index from zero) line
while not eof(musicfile) do begin
readln(musicfile, line); // read the line into a variable
if (i = 4) then // if we are at the 5th line, replace line
writeln(newfile, 'The string which should replace the 5th line')
else // just copy the line
writeln(newfile, line);
i := i + 1;
end;
Close(musicfile);
Close(newfile);

As someone who doesn't want to create a new file but wants to rewrite an old one I use TStringList (tested in lazarus btw):
var fileStrList:TStringList;
begin
fileStrList:= TStringList.Create; //creating the TStringList
try
fileStrList.LoadFromFile('AlbumList.dat'); //Loading file into TStringList
fileStrList[4]:='Text you want to replace line 5 with'; //rewriting line 5
fileStrList.SaveToFile('AlbumList.dat'); //saving rewritted TStringList to file
finally
fileStrList.Free; //freeing the TStringList !don't forget about this!
end;
end;

Related

SSIS Script howto append text to end of each row in flat file?

I currently have a flat file with around 1million rows.
I need to add a text string to the end of each row in the file.
I've been trying to adapt the following code but not having any success :-
public void Main()
{
// TODO: Add your code here
var lines = System.IO.File.ReadAllLines(#"E:\SSISSource\Source\Source.txt");
foreach (string item in lines)
{
var str = item.Replace("\n", "~20221214\n");
var subitems = str.Split('\n');
foreach (var subitem in subitems)
{
// write the data back to the file
}
}
Dts.TaskResult = (int)ScriptResults.Success;
}
I can't seem to get the code to recognise the carriage return "\n" & am not sure howto write the row back to the file to replace the existing rather than add a new row. Or is the above code sending me down a rabbit hole & there is an easier method ??
Many thanks for any pointers &/or assistance.
Read all lines is likely getting rid of the \n in each record. So your replace won't work.
Simply append your string and use #billinKC's solution otherwise.
BONUS:
I think DateTime.Now.ToString("yyyyMMdd"); is what you are trying to append to each line
Thanks #billinKC & #KeithL
KeithL you were correct in that the \n was stripped off. So I used a slightly amended version of #billinKC's code to get what I wanted :-
string origFile = #"E:\SSISSource\Source\Sourcetxt";
string fixedFile = #"E:\SSISSource\Source\Source.fixed.txt";
// Make a blank file
System.IO.File.WriteAllText(fixedFile, "");
var lines = System.IO.File.ReadAllLines(#"E:\SSISSource\Source\Source.txt");
foreach (string item in lines)
{
var str = item + "~20221214\n";
System.IO.File.AppendAllText(fixedFile, str);
}
As an aside KeithL - thanks for the DateTime code however the text that I am appending is obtained from a header row in the source file which is being read into a variable in an earlier step.
I read your code as
For each line in the file, replace the existing newline character with ~20221214 newline
At that point, the value of str is what you need, just write that! Instead, you split based on the new line which gets you an array of values which could be fine but why do the extra operations?
string origFile = #"E:\SSISSource\Source\Sourcetxt";
string fixedFile = #"E:\SSISSource\Source\Source.fixed.txt";
// Make a blank file
System.IO.File.WriteAllText(fixedFile, "");
var lines = System.IO.File.ReadAllLines(#"E:\SSISSource\Source\Source.txt");
foreach (string item in lines)
{
var str = item.Replace("\n", "~20221214\n");
System.IO.File.AppendAllText(fixedFile, str);
}
Something like this ought to be what you're looking for.

Moving file E93: More than one match

The following function works (it opens and moves the desired file to a new or preexisting directory). But, I receive an error message concerning line 11 of the function execute 'bwipeout '.expand(s:oldFileName). The error I receive is E93: More than one match for <the old file name>. I don't understand how this is possible because it has already successfully moved the file to the s:newFileName and the old file has been deleted. The new file's buffer doesn't have the same name as the old buffer. So, how would there be more than one match for the name of the old buffer?
command! -nargs=0 -bar MoveFile call s:functionMoveFile()
function s:functionMoveFile() abort
call dirvish#open("edit", 0)
let s:oldFileName = expand("%:p")
call inputsave()
let s:newFileName = input("Move file here: ",expand(s:oldFileName),"file")
call inputrestore()
if s:newFileName != '' && s:newFileName != s:oldFileName
execute 'sav '.fnameescape(s:newFileName)
let s:newFileDirectory = expand("%:p:h")
call delete(s:oldFileName)
execute 'Dirvish '.expand(s:newFileDirectory)
execute 'bwipeout '.expand(s:oldFileName)
endif
endfunction
I can prepend silent! to line 11 to avoid the error message. But, that isn't a proper fix. I don't know what else I should try because I am not asking vim to wipeout the new buffer and the old file's name doesn't match the new one. The command works as desired, but I would like to know what is incorrect about what I'm doing.
Thank you for your help.

How do I append text to the start, middle, and end of each line from one file to another using python3?

I am writing a script to change the formatting of the text from one file, and create a new text file with the changes in formatting.
I have been able to remove unwanted characters, but haven't found a way to append text to the beginning of every line in the file.
Content from the original file looks like:
DMA 123 USA 12345
What I need it to look like after appending data to the start, middle, and end of the string:
<option label="DMA 123 USA" value="123"></option>
I have almost 100 lines that vary some, but follow the above formatting. I am trying to automate this as it will be a frequent task to adjust the original file to the new format for web publishing
I have been searching and haven't found any way to do it yet. Here is my current code:
path = 'file.txt'
tvfile = open(path,'r')
days = tvfile.read()
new_path = 'tvs.txt'
new_days = open(new_path,'w')
replace_me = ['-' ,'(' ,')' ,',' , '"' , ]
for item in replace_me:
days = days.replace(item,'')
days = days.strip()
new_days.write(days)
print(days)
tvfile.close()
new_days.close()
Nit: you need to prepend, not append. That said, try something along these lines:
buffer = ""
for item in replace_me:
line = "<option label=\""
line = line + days.replace(item,'').strip()
line = line + "\"></option>"
buffer = buffer + line
new_days.write(buffer)

Supercsv :The output csv file has a messed up rows

I am currently using SuperCSV (v 2.4.0) for exporting data.
I am stuck in with the below problem.
※My problem:
- My CSV header has 9 columns
-There is a line which missing a comma dilimiter (,) between two fields, so that line become a 8-columns line
- The messing line is occur randomly, not exact the same line for every exporting.
※Here my code:
① CSV Writing function
// obmitting
stmt = con.prepareStatement(sql);
rs = stmt.executeQuery();
// obmitting
// ............
fos = new FileOutputStream(folderPath + "/" + FILE_NAME);
osw = new OutputStreamWriter(fos, "EUC-JP");
beanWriter = new CsvBeanWriter(osw, csvType);
beanWriter.writeHeader(this.CSV_HEADER);
while(rs.next()) {
AttachmentsBean bean = new AttachmentsBean();
bean.setCompDispId(pMng.getCompDispId());
bean.setFileId(rs.getString(1));
bean.setDocumentId(rs.getString(2));
bean.setFileName(rs.getString(3));
bean.setDiscription(rs.getString(4));
bean.setFileSize(rs.getString(5));
bean.setFilePath(rs.getString(6));
bean.setMimetype(rs.getString(7));
bean.setFileOrder(rs.getString(8));
progressCount++;
//出力
beanWriter.write(bean, this.CSV_HEADER);
}
//CSV出力終了
IOUtils.closeQuietly(beanWriter);
IOUtils.closeQuietly(osw);
IOUtils.closeQuietly(fos);
//文字変換
CommonUtil.convertFile(folderPath, folderPath +"/"+ FILE_NAME);
② ConvertFile helper function
this function is convert special character from EUC to UTF-8
※My question is, is my problem caused by superCSV bug ? can anyone help to figure out the cause ?
because i have read from the below discussion, maybe not only i meet the mess up csv problem, but some one did too.
Messed up CSV leads to Exception

Unable to delete file through function in Scilab

I have written the following code to plot a graph with the data present in the 'datafile'. After the graph has been plotted, I want to delete the file.
function plot_torque(datafile)
//This will call a datafile and plot the graph of net_torque vs. time
verbose = 1;
// Columns to plot
x_col = 1;
y_col = 2;
// open the datafile
file1 = file('open', datafile,'old');
data1 = read(file1, -1, 4);
time = data1(:,x_col);
torque = data1(:,y_col);
plot(time, torque, '.-b');
xtitle("Torque Generated vs. Time" ,"Time(s)" , "Torque Generated(Nm/m)");
file('close',file());
//%________________%
endfunction
In the place that I have marked as //%________% I have tried
deletefile(datafile);
and
mdelete(datafile);
None of them have worked.
And I have set the working directory to where the above '.sci' file is present and the 'datafile' is present. I am using scilab-5.4.1.
You probably leave (left) the file open. Try this:
fil="d:\Attila\PROJECTS\Scilab\Stackoverflow\file_to_delete.txt"; //change it!
fprintfMat(fil,rand(3,3),"%.2g"); //fill with some data
fd=mopen(fil,"r"); //open
//do something with the file
mclose(fd); //close
//if you neglect (comment out) this previous line, the file remains open,
//and scilab can not delete it!
//If you made this "mistake", first you should close it by executing:
// mclose("all");
//otherwise the file remains open until you close (and restart) Scilab!
mdelete(fil); //this works for me