MATLAB:如何在文件的开头插入一行文本? [英] MATLAB: How do you insert a line of text at the beginning of a file?
问题描述
选项1 :
我建议从MATLAB内部调用一些系统命令。 Windows上的一种可能性是将新的文本行写入自己的文件,然后使用 DOS 命令
!for%f in(file1.txt,file2.txt )键入%f>> new.txt
我使用了 !
(bang)operator 来调用在MATLAB中。上面的命令按顺序将file1.txt和file2.txt的内容传送给文件new.txt。请记住,您可能必须以第一个换行符来结束第一个文件,才能正确地追加内容。
上述命令的另一种替代方法是: / p>
!for%f in(file2.txt)do type%f>> file1.txt
将file2.txt的内容附加到file1.txt ,导致包含连接文本的file1.txt,而不是创建一个新文件。
如果你有你的文件名字符串,你可以创建命令作为字符串并使用 SYSTEM 命令,而不是使用!
运算符。例如:
a ='file1.txt';
b ='file2.txt';
system(['for'f in('b')do type%f>>'a'']);
选项2:
只有一个MATLAB解决方案,除了
) line'13 10 fileread('file.txt')],'delimiter',''); dlmwrite('file.txt',['第一个文件/ 1639423#1639423> Amro's
这个使用 FILEREAD 将文本文件的内容读入一个字符串,连接你想要添加的新行(连同用于回车符和换行符/新行的ASCII码),然后用 DLMWRITE 。
I得到的感觉选项#1可能比这个纯粹的MATLAB解决方案对于巨大的文本文件执行速度更快,但是我不确定。 ;)
I have a file full of ascii data. How would I append a string to the first line of the file? I cannot find that sort of functionality using fopen (it seems to only append at the end and nothing else.)
Option 1:
I would suggest calling some system commands from within MATLAB. One possibility on Windows is to write your new line of text to its own file and then use the DOS for command to concatenate the two files. Here's what the call would look like in MATLAB:
!for %f in ("file1.txt", "file2.txt") do type "%f" >> "new.txt"
I used the !
(bang) operator to invoke the command from within MATLAB. The command above sequentially pipes the contents of "file1.txt" and "file2.txt" to the file "new.txt". Keep in mind that you will probably have to end the first file with a new line character to get things to append correctly.
Another alternative to the above command would be:
!for %f in ("file2.txt") do type "%f" >> "file1.txt"
which appends the contents of "file2.txt" to "file1.txt", resulting in "file1.txt" containing the concatenated text instead of creating a new file.
If you have your file names in strings, you can create the command as a string and use the SYSTEM command instead of the !
operator. For example:
a = 'file1.txt';
b = 'file2.txt';
system(['for %f in ("' b '") do type "%f" >> "' a '"']);
Option 2:
One MATLAB only solution, in addition to Amro's, is:
dlmwrite('file.txt',['first line' 13 10 fileread('file.txt')],'delimiter','');
This uses FILEREAD to read the text file contents into a string, concatenates the new line you want to add (along with the ASCII codes for a carriage return and a line feed/new line), then overwrites the original file using DLMWRITE.
I get the feeling Option #1 might perform faster than this pure MATLAB solution for huge text files, but I don't know that for sure. ;)
这篇关于MATLAB:如何在文件的开头插入一行文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!