The example code is as following:
currentdirectory = NotebookDirectory[];
SetDirectory[currentdirectory];
datapath = FileNameJoin[{currentdirectory, "store.txt"}];
Steps = 3;
For[ii = 1, ii <= Steps, ii++,
testlist = {1, 2, 0, 0};
WriteLine[datapath, testlist];
]
When I Quit Kernel or Close the code and Run it again, I cannot continue writing data to the exist text file. The store.txt is always rewritten instead of being continuing data writing.
The solution I do is that I first load the store.txt and rewrite it again , then I continue to write data to store.txt, the code is the following:
currentdirectory = NotebookDirectory[];
SetDirectory[currentdirectory];
datapath = FileNameJoin[{currentdirectory, "store.txt"}];
If[FileExistsQ[datapath] == True,
storelist = Import["store.txt"];
WriteLine[datapath, storelist];
];
Steps = 3;
For[ii = 1, ii <= Steps, ii++,
testlist = {1, 2, 0, 0};
WriteLine[datapath, testlist];
];
From the store.txt file, we can see the data is continuing written in the text file.
In the above example, I use Steps=3
. Actually it will be a large number such as 10000 or even large. So I think my solution is not efficient.
I wonder whether there is any way to make it quick or that I don't need to load the data and rewrite first. Thank you very much!
Updates: @enano9314 suggests using OpenAppend
which I wrote is as following:
currentdirectory = NotebookDirectory[];
SetDirectory[currentdirectory];
datapath = FileNameJoin[{currentdirectory, "store.txt"}];
If[FileExistsQ[datapath] == True,
flag = 0;
str = OpenAppend[File[datapath]],
flag = 1;
str = datapath;
];
Steps = 3;
For[ii = 1, ii <= Steps, ii++,
testlist = {1, 1, 1, 1};
WriteLine[str, testlist];
];
If[flag = 0;
Close[str],
Close[File[str]];
];
Comments
Post a Comment