Reading and Writing Text Files

Asked 2 years ago, Updated 2 years ago, 43 views

I want to read the contents of the text file, change the format, and print it to another file.

Now that I can read the full text and write it to a new text file with the code below, what kind of code should I write to change the format?

Original text file

116
11/2/2012 18:22
N945.483 E1030.495
416 meters
117
11/2/2012 18:22
N945.483 E1030.495
415 meters

rewrite text file

 116, 11/2/2012 18:22, N945.483 E10 30.495,416m
117, 11/2/2012 18:22, N945.483 E10 30.495, 415m

source code

using System;
using System.Collections.General;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Reading_textfile
{
    class program
    {
        static void Main (string[]args)
        {
            string filePath=@"C:\Users\ryuma\Downloads\Elephantread.txt";

            // string [ ] Lines = File.ReadAllLines (filePath);

            List<string>lines=new List<string>();
            lines=File.ReadAllLines(filePath).ToList();

            foreach (String line in lines)
            {
                Console.WriteLine(line);
            }

            stringfilePath2=@"C:\Users\ryuma\OneDrive\Desktop\WriteFile.txt";
            File.WriteAllLines(filePath2,lines);
            Console.ReadLine();
        }
    }
}

c#

2022-09-30 15:31

4 Answers

Define the following ChunkUntil extension methods to write neatly:

public static class Extensions {
    public static IEnumerable<IList<T>>ChunkUntil>T> (this IEnumerable<T>source,Func<T,bool>endChunk) {
        var list = new List <T>();
        foreach(var item in source) {
            list.Add(item);
            if(endChunk(item)){
                yield return list;
                list = new List <T>();
            }
        }
        if (0<list.Count)
            yield return list;
    }
}

The code to call is

var filePath=@"C:\Users\ryuma\Downloads\Elephantread.txt";
varfilePath2=@"C:\Users\ryuma\OneDrive\Desktop\WriteFile.txt";
var allLines=File.ReadLines(filePath)
    .ChunkUntil(line=>Regex.IsMatch(line, "m$"))
    .Select(lines=>String.Join(", ", lines));
File.WriteAllLines (filePath2, allLines);


2022-09-30 15:31

Using string[] rather than list<string> would be better if you were simply converting.
This:

List<string>lines=new List<string>();;
lines=File.ReadAllLines(filePath).ToList();

Do this:

string[]lines=File.ReadAllLines(filePath);
char[]nl={'\n'};
lines=string.Join(",",", lines).Replace("m,", "m\n").Split(nl, StringSplitOptions.RemoveEmptyEntries);

The following actions are summarized in one line separately from the definition of the split code.
(Depending on how you do it, it may also be included in one line)

  • Connect all lines with commas
  • Change the comma immediately after m to a new line code by taking advantage of the last column ending with a blank space and m
  • Separate into string[] by specifying a new line code

If you don't need StringSplitOptions, here is one line of conversion.

lines=string.Join(",", ", lines).Replace("m,", "m\n").Split('\n');

add
After that, I dealt with the conditions of the question that was asked to the English website (+assuming that I added it without permission).
Reading and writing textfile

  • The English site added the possibility of a blank line between the data.
  • Related to that, there may also be spaces before and after the data.
  • Also, I took it in because there was a platform support for new line codes during operation in English.
  • Also, Split() has been removed and the writing method has been changed since there is no need to separate lines when writing.

The following is true:

 string line=string.Join(",",", lines.Where(//Connect all valid data in commas
   s=>!string.IsNullOrWhiteSpace(s))// Pre-extract non-blank lines
      .Select(s=>s.Trim())//Pre-remove spaces before and after strings
         Convert comma after .Replace("m,", "m" + System.Environment.NewLine)//"m" to new line
   + System.Environment.NewLine;//Finally, add a new line

stringfilePath2=@"C:\Users\ryuma\OneDrive\Desktop\WriteFile.txt";
File.WriteAllText(filePath2,line); // WriteAllText because it is a single string without segmentation


2022-09-30 15:31

I want to read the contents of the text file, change the format, and print it to another file.
My professor asked me to use the list if possible.

A straightforward implementation of the requirements would look like this:

using System;
using System.IO;
using System.Text;
using System.Collections.General;

namespace console1
{
    class program
    {
        static void Main (string[]args)
        {
            string inFile=@"Elephantread.txt";
            string outFile=@"WriteFile.txt";

            using(StreamReader sr=new StreamReader(inFile))
            using(StreamWriter sw = new StreamWriter(outFile))
            {
                while(!sr.EndOfStream){
                    StringBuilder sb = new StringBuilder();
                    var list = new List <string >();
                    list.Add(sr.ReadLine());
                    list.Add(sr.ReadLine());
                    list.Add(sr.ReadLine());
                    list.Add(sr.ReadLine());
                    sw.WriteLine(string.Join(", ", list));
                }
            }
        }
    }
}

The specifications for converting input files to output files are not clear, so

Convert the entered line into one comma-separated line by four lines and output it.

The implementation assumes that

There was no specification that m would be the end of the line, so I didn't include m end of the line.

If the number of lines entered is not divisible by four,

117,,,

The output is comma-separated as shown in .

The feature of this implementation is that even if the input file is super large (4G or higher), it can be converted without running out of memory.


2022-09-30 15:31

I wrote it down for a moment.How about like this?
I didn't test it.If the newline character is CR/LF, change it in a timely manner.

using System;
using System.Collections.General;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Reading_textfile
{
    class program
    {
        static void Main (string[]args)
        {
            string filePath=@"C:\Users\ryuma\Downloads\Elephantread.txt";

            // string [ ] Lines = File.ReadAllLines (filePath);

            List<string>lines=new List<string>();
            lines=File.ReadAllLines(filePath).ToList();

            foreach (String line in lines)
            {
                Console.WriteLine(line);
            }

            List<string>lines2 = new List<string>();// Creating a List for Output

            string a="; // Variable for output string
            foreach (string line in lines)
            {

                If(line.Contains("m")==true)//m is included, end one line
                {
                    a+=line;
                    lines2.Add(a); // Add to line2
                    a=";// Clear for the next line.
                } else
                {
                    If a+=line.Replace("\n", "", "); //m is not included, change the newline character to , and add it.
                }
            }

            stringfilePath2=@"C:\Users\ryuma\OneDrive\Desktop\WriteFile.txt";
            File.WriteAllLines(filePath2,lines2);
            Console.ReadLine();
        }
    }
}


2022-09-30 15:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.