Create a .txt file if doesn't exist, and if it does append a new line
Use the correct constructor:
else if (File.Exists(path))
{
using(var sw = new StreamWriter(path, true))
{
sw.WriteLine("The next line!");
}
}
Writing to a new file if it doesn't exist, and appending to a file if it does
It's not clear to me exactly where the high-score that you're interested in is stored, but the code below should be what you need to check if the file exists and append to it if desired. I prefer this method to the "try/except".
import os
player = 'bob'
filename = player+'.txt'
if os.path.exists(filename):
append_write = 'a' # append if already exists
else:
append_write = 'w' # make a new file if not
highscore = open(filename,append_write)
highscore.write("Username: " + player + '\n')
highscore.close()
c# - How to create a file if it doesn't exist yet and add new text?
Try this
string path = @"Your File Path";
bool done = false;
while (!done)
{
done = true;
try
{
FileStream fileStream = null;
fileStream = File.Open(path, File.Exists(path) ? FileMode.Append : FileMode.OpenOrCreate);
using (StreamWriter fs = new StreamWriter(fileStream))
{
fs.WriteLine(fileStream.Length == 0 ? "Text A" : "Text B");
};
fileStream.Close();
}
catch (IOException)
{
done = false;
}
}
How to insert data into a text file if the data doesn't exist already (Python)
You were pretty close, but because you open the file to append to it, it starts with the file pointer at the end. You need to seek to the start to read its contents again:
def writeSite(site):
file = open("websites.txt", 'a+')
file.seek(0)
# print(site)
if site in file.read():
return
file.write(site + "\n")
file.close()
However, keep in mind that site in file.read()
is very crude.
For example, imagine you already have 'http://somesite.com/page/'
in the file but now you want to add 'http://somesite.com/'
- the URL as a whole is not in the file, but your test will find it.
If you want to check whole lines (and be sure you deal with the file nicely), this would be better:
def writeSite(site):
site += '\n'
with open("websites.txt", 'a+') as f:
f.seek(0)
if site in f.readlines():
return
f.write(site)
It adds a newline to the name of the site to separate the URLs in the file and uses readlines to make use of that fact to check for the whole URL. Using with
ensures the file always gets closed.
And since you want to read before writing anyway, you could use 'r+'
as a mode, and skip the seek - but only if you can be sure the file already exists. I assume you chose 'a+'
because that isn't the case.
(in case you worry that this changes the value of site
- that's only true for the parameter inside the function. Whatever value you passed in outside the function will remain unaffected)
Create File If File Does Not Exist
You can simply call
using (StreamWriter w = File.AppendText("log.txt"))
It will create the file if it doesn't exist and open the file for appending.
Edit:
This is sufficient:
string path = txtFilePath.Text;
using(StreamWriter sw = File.AppendText(path))
{
foreach (var line in employeeList.Items)
{
Employee e = (Employee)line; // unbox once
sw.WriteLine(e.FirstName);
sw.WriteLine(e.LastName);
sw.WriteLine(e.JobTitle);
}
}
But if you insist on checking first, you can do something like this, but I don't see the point.
string path = txtFilePath.Text;
using (StreamWriter sw = (File.Exists(path)) ? File.AppendText(path) : File.CreateText(path))
{
foreach (var line in employeeList.Items)
{
sw.WriteLine(((Employee)line).FirstName);
sw.WriteLine(((Employee)line).LastName);
sw.WriteLine(((Employee)line).JobTitle);
}
}
Also, one thing to point out with your code is that you're doing a lot of unnecessary unboxing. If you have to use a plain (non-generic) collection like ArrayList
, then unbox the object once and use the reference.
However, I perfer to use List<>
for my collections:
public class EmployeeList : List<Employee>
open() in Python does not create a file if it doesn't exist
You should use open
with the w+
mode:
file = open('myfile.dat', 'w+')
Create a .txt file if doesn't exist with user inputted data
Here is an example of how to store files to the logged in users My Documents folder on windows.
You can modify the AppendUserFile function to support other file modes. This version will open the file for Appending if it exists, or create it if it doesn't exist.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
AppendUserFile("example.txt", tw =>
{
tw.WriteLine("I am some new text!");
});
Console.ReadKey(true);
}
private static bool AppendUserFile(string fileName, Action<TextWriter> writer)
{
string path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
string filePath = Path.Combine(path, fileName);
FileStream fs = null;
if (File.Exists(filePath))
fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.Read);
else
fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Read);
using (fs)
{
try
{
TextWriter tw = (TextWriter)new StreamWriter(fs);
writer(tw);
tw.Flush();
return true;
}
catch
{
return false;
}
}
}
}
}
Text Files, and New Lines
You can use replace:
def create():
path = input("What file would you like to create: ")
output_file = open(path, 'x')
text = input("What would you like to write? ")
output_file.write(text.replace('\\n', '\n'))
output_file.close()
def append():
path = input("What file would you like to append: ")
output_file = open(path, 'a')
text = input("What would you like to write?")
output_file.writelines(text.replace('\\n', '\n'))
output_file.close()
write = input("Would you like to write something today, or edit? ")
if write == "Write":
create()
if write == "Edit":
append()
Related Topics
Post-Increment Within a Self-Assignment
How to Embed My Own Fonts in a Winforms App
"An Internal Error Occurred." When Loading Pfx File with X509Certificate2
How to Know If a Cell Has an Error in the Formula in C#
Differences Between Expandoobject, Dynamicobject and Dynamic
Inheriting Comments from an Interface in an Implementing Class
Best Way to Handle Integer Overflow in C#
How to Run Something in the Sta Thread
Determine Label Size Based Upon Amount of Text and Font Size in Winforms/C#
Add Custom Header in Httpwebrequest
Datetime to String with Time Zone
Random Errors Using Wait for Element Clickable Method in Selenium
Passing Data Between Winforms Forms
System.Threading.Timer in C# It Seems to Be Not Working. It Runs Very Fast Every 3 Second