如何打开文件并阅读它们

如何打开文件并阅读它们

本文介绍了PHP-如何打开文件并阅读它们,然后用"x"写新文件.每个文件行数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我之前在这里发布了此问题,但没有任何回复.我可能做错了什么,所以这里还是有更多详细信息.

目录中的文件名为1.txt,2.txt,3.txt等....下面的代码段进入该目录,打开所有读取它们的* .txt文件,删除重复项并创建一个文件具有所有独特的内容. (在这种情况下为名称).

$files = glob($dirname."/*.txt"); //matches all text files
    $lines = array();
    foreach($files as $file)
    {
    $lines = array_merge($lines, file($file, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES));
    }
    $lines = array_unique($lines);
    file_put_contents($dirname."/allofthem.txt", implode("\n", $lines));
    }

以上对我非常有用!多亏了stackoverflow的大力帮助.

但是,我希望更进一步.

代替一个大的免费重复文件"allofthem.txt",我该如何修改上面的代码以从新数据中创建每行最多5oo行的文件?

他们需要进入一个新目录,例如$ dirname."/done/".$ i.".txt,我试图在循环中计数,但是我的努力没有奏效,结果却是一英里长. /p>

我还尝试将500推入一个数组,递增到另一个数组并保存该方式.没运气.我只是没有得到"它.

同样,这位初学者需要一些专家帮助.预先感谢.

解决方案

一旦按照代码排列了行,就可以使用 array_chunk ,然后将每个块写入其自己的文件:

// ... from your code
$lines = array_unique($lines);

$counter = 1;
foreach (array_chunk($lines, 500) as $chunk)
{
  file_put_contents($dirname . "/done/" . $counter . ".txt", implode("\n", $chunk));
  $counter++;
}

I posted this question here before but there were no responses. I may have done something wrong so, here it is again with some more details.

The files in the directory are named 1.txt, 2.txt, 3.txt etc.... The snippet below enters that directory, opens all the *,txt files reading them, removes the dupes and creates one file with all the unique contents. (names in this case).

$files = glob($dirname."/*.txt"); //matches all text files
    $lines = array();
    foreach($files as $file)
    {
    $lines = array_merge($lines, file($file, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES));
    }
    $lines = array_unique($lines);
    file_put_contents($dirname."/allofthem.txt", implode("\n", $lines));
    }

The above works great for me! Thanks to great help here at stackoverflow.

But, I desire to take it one step further.

Instead of one big duplicate free "allofthem.txt" file, how can I modify the above code to create files with a maximum of 5oo lines each from the new data?

They need to go into a new directory eg $dirname."/done/".$i.".txt" I have tried counting in the loop but my efforts are not working and ended up being a mile long.

I also attempted to push 500 into an array, increment to another array and save that way. No luck. I am just not "getting" it.

Again, this beginner needs some expert assistance. Thanks in advance.

解决方案

Once you have your array of lines as per your code, you can break it into chunks of 500 lines using array_chunk, and then write each chunk to its own file:

// ... from your code
$lines = array_unique($lines);

$counter = 1;
foreach (array_chunk($lines, 500) as $chunk)
{
  file_put_contents($dirname . "/done/" . $counter . ".txt", implode("\n", $chunk));
  $counter++;
}

这篇关于PHP-如何打开文件并阅读它们,然后用"x"写新文件.每个文件行数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 13:34