首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >打开多个文件并将其数据写入一个文件中,包括换行。

问打开多个文件并将其数据写入一个文件中,包括换行。
EN

Stack Overflow用户
提问于 2017-01-09 17:57:01
回答 2查看 328关注 0票数 1

我有多个.m3u文件,其中包含以下字符串:

代码语言:javascript
复制
string1
string2 etc //(with the line break)

我想将这个信息添加到一个文件中,但是当它到达文件的末尾时,添加一个中断行。因为当我执行代码时,它可以工作,但是当它连接下一个文件时,我得到的结果如下:

代码语言:javascript
复制
string10
string11string12
string13

我想防止这种情况,并将所有内容添加到新行中。代码如下:

代码语言:javascript
复制
<?PHP
//File path of final result
$longfilepath = "/var/lib/mpd/playlists/";

$filepathsArray = [$longfilepath."00's.m3u",$longfilepath."50's.m3u",$longfilepath."60's.m3u",$longfilepath."70's.m3u",$longfilepath."80's.m3u",$longfilepath."90's.m3u",$longfilepath."Alternative Rock.m3u",$longfilepath."Best Of Irish.m3u",$longfilepath."Blues.m3u",$longfilepath."Chart Hits.m3u",$longfilepath."Christmas.m3u",$longfilepath."Classic Rock.m3u",$longfilepath."Classical Opera.m3u",$longfilepath."Country.m3u",$longfilepath."Dance.m3u",$longfilepath."Disco.m3u",$longfilepath."Easy Listening.m3u",$longfilepath."Electric Rock.m3u",$longfilepath."Hard Rock.m3u",$longfilepath."Irish Country.m3u",$longfilepath."Jazz.m3u",$longfilepath."Live and Acoustic.m3u",$longfilepath."Love Songs.m3u",$longfilepath."Pop.m3u",$longfilepath."Rap and RnB.m3u",$longfilepath."Reggae.m3u",$longfilepath."Relaxation.m3u",$longfilepath."Rock and Roll.m3u",$longfilepath."Rock.m3u",$longfilepath."Soul.m3u",$longfilepath."Soundtracks.m3u",$longfilepath."Top Bands.m3u"];
$filepath = "mergedfiles.txt";

$out = fopen($filepath, "w");
//Then cycle through the files reading and writing.

foreach($filepathsArray as $file){
  $in = fopen($file, "r");
  while ($line = fgets($in)){
       fwrite($out, $line."\n"); //My attempt to add new line (which works) but then adds an extra for those that dont need it.
  }
  fclose($in);
}

//Then clean up
fclose($out);
?>

我用:

代码语言:javascript
复制
fwrite($out, $line."\n");

但我得到的结果如下:

代码语言:javascript
复制
string1

string2
string3

string4

string5
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-01-09 18:01:46

在添加自己的换行符之前-删除所有可以在字符串中使用trim (甚至空行)的换行符:

代码语言:javascript
复制
foreach($filepathsArray as $file){
  $in = fopen($file, "r");
  while ($line = fgets($in)) {
       $line = trim($line);
       if ($line) {
           // if line is not empty - write it to a file
           fwrite($out, $line . "\n");
       }
  }
  fclose($in);
}
票数 2
EN

Stack Overflow用户

发布于 2017-01-09 18:04:29

这可能更容易:

代码语言:javascript
复制
$out = array();
foreach($filepathsArray as $file) {
    $out = array_merge($out, file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
}
file_put_contents($filepath, implode("\n", $out));
  • 将文件读入数组中,忽略换行符和空行。
  • 使用换行符内爆数组并将其写入最终文件

注意:您可能需要在\r\n上内爆,以便在一些Windows应用程序(如记事本)中看到换行符。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41554013

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档