如何同时访问一个文件来添加/编辑/删除数据?
我想创建一个文本文件并向其中逐行添加数据。如果文件中已存在数据行,则应将其忽略。否则,应将其附加到文件中。
I want to create a text file and add data to it, line by line. If a data line already exists in the file, it should be ignored. Otherwise, it should be appended to the file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
几乎可以肯定,您最好阅读该文件并编写新的更改版本。在大多数情况下,它会更快、更容易、更不容易出错并且更具可扩展性。
You are almost certainly better to read the file and write a new changed version. In most circumstances it will be quicker, easier, less error-prone and more extensible.
如果你的文件不是那么大,你可以这样做:
但是,如果你必须担心并发性、文件中存储的大量数据,或者基本上除了快速处理之外的任何事情,这不是一个好主意和一次性的。
If your file isn't that big, you could just do something like this:
But this isn't a great idea if you have to worry about concurrency, large amounts of data being stored in the file, or basically anything other than something quick and one-off.
我是这样做的,
I did it like this,