I was wondering how do I get a line into an array with lua in some sort of function
eg. FileToArray("C:/file.txt")?
I know I can use:
var = io.open("file")
Data = var:read()
But it only returns the 1st line, and no other lines.
Anyone know how to fix this or a different way? I'm new to lua and the file system stuff.
You can pass "*a" to read function, it should read the whole file:
local file = io.open("file-name", "r");
local data = file:read("*a")
And if you want to store each line in an array. Like Jane's solution you can use
io:lines () - which returns iterator function (each call gives you a new line)
local file = io.open("file-name", "r");
local arr = {}
for line in file:lines() do
table.insert (arr, line);
end
local file = io.open("c:\\file.txt")
local tbllines = {}
local i = 0
if file then
for line in file:lines() do
i = i + 1
tbllines[i] = line
end
file:close()
else
error('file not found')
end
See: http://lua-users.org/wiki/IoLibraryTutorial for more information.
Related
I am trying to write a MATLAB function that extends the "save" command to create the specified path if it doesn't already exist. I have been successful with a single variable, but not with multiple variables. With multiple variables, I receive the following error message:
31 variables_to_save(i) = variable_name;
Conversion to cell from char is not possible.
Error in saveMatVars (line 31)
variables_to_save(i) = variable_name;
Here is my function:
function saveMatVars( file_path, varargin )
%saveMatVars saves variables in varargin to file specified in file_path, creating the file path if it doesn't exist
% varargin is the variables to save
% get path and filename from file_path
[parent_folder, ~] = fileparts(file_path);
% if parent_folder doesn't exist, create it
if ~exist(parent_folder, 'dir')
mkdir(parent_folder);
end
% get names of variables to save
num_vars = length(varargin);
switch num_vars
case 0
return
case 1
variable_name = inputname(2);
variable_name = matlab.lang.makeValidName(variable_name);
variable_val = varargin{1};
feval(#()assignin('caller', variable_name, variable_val)); % create
a dummy function so I can access the current function's workspace
variables_to_save = variable_name;
otherwise % note - this part does not work
variables_to_save = cell(1,1);
for i = 1:num_vars
variable_name = inputname(i+1);
variable_name = matlab.lang.makeValidName(variable_name);
variable_val = varargin{i};
feval(#()assignin('caller', variable_name, variable_val)); % create a dummy function so I can access the current function's workspace
variables_to_save(i) = variable_name;
end
variables_to_save = string(variables_to_save);
end
% save variables_to_save in file_path
save(file_path, variables_to_save);
return
end
The documentation on "save" says the following about the variables to save:
save(filename,variables) saves only the variables or fields of a structure array specified by variables.
I have tried various functions for converting char arrays to strings and to cell arrays to no avail.
i have some problem in my array2d. i actually want plan to have refresh command.
my data on data.txt
test1:30:1
test2:40:2
So whenever i call function ReadData. It will send to my Array2d something like this :
line_data = {{"test1", "30", "1"},
{"test2", "40", "2"}}
But the problem is every i call the function. it will always adding same data, i would like to just do refresh or replace maybe, when i do some event.
my code
line_data = {}
function ReadData()
local file = io.open("data.txt", "r")
for line in file:lines() do
line_data[#line_data+1] = { line:match('([^:]+):(%d+):(%d+)') }
end
end
maybe you guys can help me with this situation ?
If I've right understand, you'll overwrite the line_data after re-reading the file. So I think the best way is to get the array from the reading function itself and replace the old one. Here my example:
function ReadData(_path)
local tmp = {}
local file = io.open(_path, "r")
for line in file:lines() do
tmp[#tmp+1] = { line:match('([^:]+):(%d+):(%d+)') }
end
file:close()
return tmp
end
function Array2dAsStr(_array)
local function cutRight(_s, _i)
_i = _i or 1
return _s:sub(1, (_s:len())-1*_i)
end
local sOut = '{'
for _, v in pairs(_array) do
sOut = sOut..'{'
for _, v1 in pairs(v) do
sOut = sOut..v1..','
end
sOut = cutRight(sOut)..'},'
end
return cutRight(sOut)..'}'
end
line_data = ReadData("data.txt")
print(Array2dAsStr(line_data))
-- if you read again the file, the old stuff from line_data will overwritten
line_data = ReadData("data.txt")
print(Array2dAsStr(line_data))
If you want to fill existing lines with new data, then you need some id. If that id is just the name, i.e. first part of string, then change line where you append data to array:
-- old code
-- line_data[#line_data+1] = { line:match('([^:]+):(%d+):(%d+)') }
-- new code
local name, score1, score2 = line:match('([^:]+):(%d+):(%d+)')
line_data[name] = {score1, score2}
I have this code:
self.y_file = with open("y_file.txt", "r") as g: y_data.append(line for line in g.readlines())
But it doesn't seem to work and I am more than sure the problem lies within 1) How I open the file (with) and that for loop. Any way I could make this work?
you can just open and read. If you want auto-close you need to wrap it in function
self.y_file = open('y_file.txt').readlines()
Or:
def read_file(fname):
with open(fname) as f:
return f.readlines()
self.y_file = read_file('y_file.txt')
I have put some values in a file. In the puppet manifests I want to get the value of these variables. Is there a specific directory to put my file? Also, what should be the format of the file?
If this file on puppet-server, you can write functions for module. For example:
modules/my_module/lib/puppet/parser/functions/get_var.rb:
$: << File.expand_path(File.join(File.dirname(__FILE__), '.'))
module Puppet::Parser::Functions
newfunction(:get_var,
:type => :rvalue) do |args|
file_name = args[0]
f = File.open(file_name)
s = f.readline()
return s
end
end
And use it in manifests: $test = get_var('/etc/puppet/configs.txt'). This function return first string from file, but you can change it for your needs.
For file on client, you can write facter.
I want to read data from a file and save it into an array. Then insert some new data into this array and then save this new data back into the same file deleting what is already there. My code works perfectly, giving me my required data, when I have 'r+' in the fopen parameters, however when I write to the file again it does not delete the data already in the file just appends it to the end as expected. However when I change the permissions to 'w+' instead of 'r+', my code runs but no data is read in or wrote to the file! Anyone know why this might be the case? My code is as seen below.
N = 1021;
b = [0;0;0;0;0];
% Opens file specified by user.
fid = fopen('testing','w+');
% Read header data
Header = fread(fid, 140);
% Move to start of data
fseek(fid,140,'bof');
% Read from end of config header to end of file and save it in an array
% called data
Data = fread(fid,inf);
Data=reshape(Data,N,[]);
b=repmat(b,[1 size(Data,2)]);
r=[b ; Data];
r=r(:);
r = [Header;r];
% write new values into file
fwrite(fid,r);
fclose(fid);
% Opens file specified by user.
fid = fopen('test');
All = fread(fid,inf);
fclose(fid);
According to the documentation, the w+ option allows you to "Open or create new file for reading and writing. Discard existing contents, if any." The contents of the file are discarded, so Data and Header are empty.
You need to set the position indicator of the filehandle before writing. With frewind(fid) you can set it to the beginning of the file, otherwise the file is written / appended at the current position.
N = 1021;
b = [0;0;0;0;0];
% Opens file specified by user.
fid = fopen('testing','r+');
% Read header data
Header = fread(fid, 140);
% Move to start of data
fseek(fid,140,'bof');
% Read from end of config header to end of file and save it in an array
% called data
Data = fread(fid,inf);
Data=reshape(Data,N,[]);
b=repmat(b,[1 size(Data,2)]);
r=[b ; Data];
r=r(:);
r = [Header;r];
% write new values into file
frewind(fid);
fwrite(fid,r);
fclose(fid);
% Opens file specified by user.
fid = fopen('test');
All = fread(fid,inf);
fclose(fid);