C#如何将文本文件拆分为多个文件
如何将一个 1000 行的文本文件拆分为多个较小的文件,例如每个 300 行?请记住,原始文件可能多于或少于一千行。
file1.txt 300 lines -> rest
file2.txt 300 lines -> rest
file3.txt 300 lines -> rest
file4.txt 100 lines
我尝试了以下方法,但它不起作用。
int counter = 0;
string line;
string lineoutput = (current_dir + "\\" + DateTime.Now.ToString("HHmmss") + ".txt");
System.IO.StreamReader inputfile;
inputfile = new System.IO.StreamReader(new_path);
while ((line = inputfile.ReadLine()) != null)
{
System.IO.StreamWriter file = new System.IO.StreamWriter(current_dir + "\\" + DateTime.Now.ToString("HHmmss") + ".txt", true);
string _replaceBackspace = ReplaceBackspace(read_file.ReadLine().ToLower());
using (StreamWriter writer = new StreamWriter(lineoutput, true))
{
if (counter == 5000)
{
counter = 0;
lineoutput = (current_dir + "\\" + DateTime.Now.ToString("HHmmss") + ".txt");
}
writer.WriteLine(line.ToLower());
}
counter++;
}
How do I split a single text file with 1000 lines into multiple smaller files of, for example, 300 lines apiece? Please keep in mind that the original file may have more or less than a thousand lines.
file1.txt 300 lines -> rest
file2.txt 300 lines -> rest
file3.txt 300 lines -> rest
file4.txt 100 lines
I tried the following but it's not working.
int counter = 0;
string line;
string lineoutput = (current_dir + "\\" + DateTime.Now.ToString("HHmmss") + ".txt");
System.IO.StreamReader inputfile;
inputfile = new System.IO.StreamReader(new_path);
while ((line = inputfile.ReadLine()) != null)
{
System.IO.StreamWriter file = new System.IO.StreamWriter(current_dir + "\\" + DateTime.Now.ToString("HHmmss") + ".txt", true);
string _replaceBackspace = ReplaceBackspace(read_file.ReadLine().ToLower());
using (StreamWriter writer = new StreamWriter(lineoutput, true))
{
if (counter == 5000)
{
counter = 0;
lineoutput = (current_dir + "\\" + DateTime.Now.ToString("HHmmss") + ".txt");
}
writer.WriteLine(line.ToLower());
}
counter++;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
最简单的情况:
Simplest case:
循环
File.ReadLines(path)
并将每一行写入StreamWriter
。保留一个计数器,每次达到
300
时,关闭StreamWriter
并打开一个新的。Loop over
File.ReadLines(path)
and write each line to aStreamWriter
.Keep a counter, and, each time it reaches
300
, close theStreamWriter
and open a new one.除了 SLAks 答案之外,您还可以使用
System.Linq
中的扩展方法Skip
和Take
来完成此操作As well as SLaks answer, you can also do it using the extension methods
Skip
andTake
inSystem.Linq
根据 bigtbl 的答案,我添加了对于生成一系列 CSV 的情况,将第一行保留为每个文件的标题。 MAX_LINES 包含总计数的标题行,这就是
start_idx
的原因。Following on the answer from bigtbl, I added, for the case of generating a series of CSVs, preservation of first row as header on each file. MAX_LINES is inclusive of the header row for total count, which is the reason for
start_idx
.完整程序:
Full program: