Update Specific Field in Text File in Specific Line

Editing specific line in text file in Python

You want to do something like this:

# with is like your try .. finally block in this case
with open('stats.txt', 'r') as file:
# read a list of lines into data
data = file.readlines()

print data
print "Your name: " + data[0]

# now change the 2nd line, note that you have to add a newline
data[1] = 'Mage\n'

# and write everything back
with open('stats.txt', 'w') as file:
file.writelines( data )

The reason for this is that you can't do something like "change line 2" directly in a file. You can only overwrite (not delete) parts of a file - that means that the new content just covers the old content. So, if you wrote 'Mage' over line 2, the resulting line would be 'Mageior'.

How to update a specific value in a specific line of a text file c#

You need to rebuild your line collection with new values. YOu need to take it apart and re-assemble

foreach(string line in lines)
{
string[] items = line.Split(',');

if (items[2] == id.ToString())
{
items[0] = EditCategoryInput;
}
newLineList.Add(string.Join(',', items )); // add your new or unchanged line to new line collection
}

How can I update specific parts of a text file in java?

If you are allowed for this project (i.e., not a school assignment), I recommend using JSON, YAML, or XML. There are too many Java libraries to recommend for using these types of files, but you can search "Java JSON library" for example.

First, need to address some issues...

It's not good practice to put Scanner scan = new Scanner(System.in); in a try-with-resource. It will auto-close System.in and won't be useable after being used in your Reader class. Instead, just do this:

Scanner scan = new Scanner(System.in);
Reader reader = new Reader(scan, path, fileWriter, fileReader);

Or, even better, don't pass it to the constructor, but just set scan to it in the constructor as this.scan = new Scanner(System.in);

Next, for fileReader, you can just initialize it similarly as you did for fileWriter:

BufferedReader fileReader = Files.newBufferedReader(path, StandardCharsets.UTF_8);

Next, this line:

BufferedWriter fileWriter = Files.newBufferedWriter(path, StandardCharsets.UTF_8)

Every time this program is run, this line will overwrite the file to empty, which is probably not what you want. You could add StandardOpenOption.APPEND, but then this means you'll only write to the end of the file.

When you update data, you also have the issue that you'll need to "push" down all of the data that comes after it. For example:

Bobby 1 2 3 4 5
Fred 1 2 3 4 5

If you change the name Bobby to something longer like Mr. President, then it will overwrite the data after it.

While there are different options, the best and simplest is to just read the entire file and store each bit of data in a class (name, scores, etc.) and then close the fileReader.

Then when a user updates some data, change that data (instance variables) in the class and then write all of that data to the file.

Here's some pseudo-code:

class MyProg {
// This could be a Map/HashMap instead.
// See updateData().
public List<Player> players = new ArrayList<>();

public void readData(String filename) throws IOException {
Path path = Paths.get(filename);

try(BufferedReader fileReader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
// Read each Player (using specific format)
// and store in this.players
}
}

public void writeData(String filename) throws IOException {
Path path = Paths.get(filename);

try(BufferedWriter fileWriter = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
// Write each Player from this.players in specific format
}
}

public void updateData() {
// 1. Find user-requested Player from this.players
// 2. Update that specific Player class
// 3. Call writeData()

// If you are familiar with Maps, then it would be faster
// to use a Map/HashMap with the key being the player's name.
}
}

class Player {
public String name;
public int games;
public int goals;
//...
}

Programmatically modifying a specific line in a text file

With sed:

sed 's/\(^dbms\.active_database=\)test\.db/\1production.db/' file

Edit a specific Line of a Text File in C#

You can't rewrite a line without rewriting the entire file (unless the lines happen to be the same length). If your files are small then reading the entire target file into memory and then writing it out again might make sense. You can do that like this:

using System;
using System.IO;

class Program
{
static void Main(string[] args)
{
int line_to_edit = 2; // Warning: 1-based indexing!
string sourceFile = "source.txt";
string destinationFile = "target.txt";

// Read the appropriate line from the file.
string lineToWrite = null;
using (StreamReader reader = new StreamReader(sourceFile))
{
for (int i = 1; i <= line_to_edit; ++i)
lineToWrite = reader.ReadLine();
}

if (lineToWrite == null)
throw new InvalidDataException("Line does not exist in " + sourceFile);

// Read the old file.
string[] lines = File.ReadAllLines(destinationFile);

// Write the new file over the old file.
using (StreamWriter writer = new StreamWriter(destinationFile))
{
for (int currentLine = 1; currentLine <= lines.Length; ++currentLine)
{
if (currentLine == line_to_edit)
{
writer.WriteLine(lineToWrite);
}
else
{
writer.WriteLine(lines[currentLine - 1]);
}
}
}
}
}

If your files are large it would be better to create a new file so that you can read streaming from one file while you write to the other. This means that you don't need to have the whole file in memory at once. You can do that like this:

using System;
using System.IO;

class Program
{
static void Main(string[] args)
{
int line_to_edit = 2;
string sourceFile = "source.txt";
string destinationFile = "target.txt";
string tempFile = "target2.txt";

// Read the appropriate line from the file.
string lineToWrite = null;
using (StreamReader reader = new StreamReader(sourceFile))
{
for (int i = 1; i <= line_to_edit; ++i)
lineToWrite = reader.ReadLine();
}

if (lineToWrite == null)
throw new InvalidDataException("Line does not exist in " + sourceFile);

// Read from the target file and write to a new file.
int line_number = 1;
string line = null;
using (StreamReader reader = new StreamReader(destinationFile))
using (StreamWriter writer = new StreamWriter(tempFile))
{
while ((line = reader.ReadLine()) != null)
{
if (line_number == line_to_edit)
{
writer.WriteLine(lineToWrite);
}
else
{
writer.WriteLine(line);
}
line_number++;
}
}

// TODO: Delete the old file and replace it with the new file here.
}
}

You can afterwards move the file once you are sure that the write operation has succeeded (no excecption was thrown and the writer is closed).

Note that in both cases it is a bit confusing that you are using 1-based indexing for your line numbers. It might make more sense in your code to use 0-based indexing. You can have 1-based index in your user interface to your program if you wish, but convert it to a 0-indexed before sending it further.

Also, a disadvantage of directly overwriting the old file with the new file is that if it fails halfway through then you might permanently lose whatever data wasn't written. By writing to a third file first you only delete the original data after you are sure that you have another (corrected) copy of it, so you can recover the data if the computer crashes halfway through.

A final remark: I noticed that your files had an xml extension. You might want to consider if it makes more sense for you to use an XML parser to modify the contents of the files instead of replacing specific lines.



Related Topics



Leave a reply



Submit