How to Write Data to a Text File Without Overwriting the Current Data

Write to text file without overwriting in Java

Just change PrintWriter out = new PrintWriter(log); to

PrintWriter out = new PrintWriter(new FileWriter(log, true));

Add new data to a text file without overwriting it in python

Open the file before the loop starts. Every time you open the file for writing, it creates a new file (it deletes whatever is in it).

with open("Monarchs Output.txt", "w") as text_file:
turn = 1
while turn < times:
dip1 = randint(1,4)
dip2 = randint(1,4)
dip = (dip1 + dip2) - 2

adm1 = randint(1,4)
adm2 = randint(1,4)
adm = (adm1 + adm2) - 2

mil1 = randint(1,4)
mil2 = randint(1,4)
mil = (mil1 + mil2) - 2

print("Monarch{}, adm: {}, dip: {}, mil: {}\n".format(turn, adm, dip, mil), file=text_file)

turn = turn + 1

How to write to a file without overwriting current contents?

Instead of "w" use "a" (append) mode with open function:

with open("games.txt", "a") as text_file:

How to add data to a file without overwriting previous data

In serialization stream use:

"FileMode.Append"

If you only Open or only Create you'll overwrite it.

Think about the fact if you append info in a file, you have to know how to read the data correctly, found where every append starts, etc... if you need it.

One more question, why are not using "using clauses"?

Edit:

public static void SerializeSignUpDetails(string userName, string password)
{
Users obj = new Users(userName, password);
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("SignUp.txt", FileMode.Append, FileAccess.Write); //here is the point. you can use File.Append or File.Open static methods.
formatter.Serialize(stream, obj);
stream.Close();
}

How to write data to a text file without overwriting the current data

Pass true as the append parameter of the constructor:

TextWriter tsw = new StreamWriter(@"C:\Hello.txt", true);


Related Topics



Leave a reply



Submit