How to read the filename of a csv file in ruby - ruby

I need to read the filename of a csv file to extract some information about what to do with the data inside the file. How do I read the filename?
e.g. I will get a file called 200_SomeTestName.csv. The file will contain details of the test to be created. I'm required to create a test called SomeTestName for the student who has an id of 200.

You can list all the CSV files in the dropbox folder and check if they match the pattern. Then extract the information you need and create the test:
Dir.glob('yourdropboxfolder/*.csv').each do |filename|
name = File.basename(filename, '.csv')
if (match = /(\d+)_(.*).csv/.match(name))
student_id = match[1]
test_name = match[2]
create_test_for(student_id, test_name, File.read(filename))
end
end
Not sure if you need to extract the values from the filename or if this information is also in the file.

Related

How can I get a Ruby Script to take a CSV File and separate it to get a specific output?

The goal of the script is to get the last name and the first and last letter of the first name and provide is as an eventual username for the useradd command. An example of this is: John Doe, The desired username would be doejn.
I can get the CSV file read into the script by using this:
(The CSV File has a Header of "First Name" and "Last Name")
employeeData = CSV.parse(File.read("employeedata.csv"), headers: true)
After that I have no clue how to use the data that is in the employeeData variable.
I am considering your employeedata.csv having a header with First Name and Last Name column
e.g of CSV file
First Name, Last Name
Rohit, Lingayat
filename = 'employeedata.csv' #*location of the file*
CSV.foreach(filename, headers: true) do |row|
first_name_char = row['First Name'].strip.split('')
useradd_name = "#{row['Last Name']}#{first_name_char.first}#{first_name_char.last}"
puts useradd_name
end
output:
LingayatRt
You can use useradd_name to use in your command or you can create an array which will be the list of all combinations of the first name and last name and you can use accordingly.
hope this solution will help you out.

Is there a way to read fixed length files using csv.reader() module in Python 2.x

I have a fixed length file like:
0001ABC,DEF1234
The file definition is:
id[1:4]
name[5:11]
phone[12:15]
I need to load this data into a table. I tried to use CSV module and defined the fixed lengths of each field. It is working fine except for the name field.
For the NAME field, only the value till ABC is getting loaded. The reason is:
As I am using CSV module, it is treating 0001ABC, as a value and only parsing till that.
I tried to use escapechar = ',' while reading the file, but it removes the ',' from the data. I also tried quoting=csv.QUOTE_ALL but that didnt work either.
with open("xyz.csv") as csvfile:
readCSV = csv.reader(csvfile)
writeCSV = open("sample_csv", 'w');
output = csv.writer(writeCSV, dialect='excel', lineterminator="\n")
for row in readCSV:
print(row) # to debug #
data= str(row[0])
print(data) # to debug #
id = data[0:4]
name = data[5:11]
phone = data[12:15]
output.writerow([id,name,phone])
writeCSV.close()
Output of the print commands:
row: ['0001ABC','DEF1234']
data: 0001ABC
Ideally, I expect to see the entire set 0001ABC,DEF1234 in the variable: data.
I can then use the parsing as mentioned in the code to break it into different fields.
Can you please let me know where I am going wrong?

json files saved with trailing "?"

I'm saving a bunch of data as a hash and saving it as a json file. Code for the saving:
def write_to_file(id, data)
Dir.chdir(File.dirname(__FILE__)+"/specs")
filename = "./"+id+".json"
File.open("#{filename}", 'w') do |f2|
f2.write(data.to_json)
end
end
I want to save it as id.json, but the file is getting saved with a "?" at the end. For example, 199015806906670?.json where the original value of "id" is 199015806806670.
If I search for 19901580606670 I am also unable to use TAB to autocomplete.
Does anyone know why this is happening?
EDIT:
Sample from file containing the ids:
104184946332304
131321736945390
693134284084652
146974018804301
288608807960773
Code to get these:
url = File.open("newapps/curlist.txt","r")
url.each_line do |line|
func1(line) #func1 calls write_to_file, no changes to line in func1
end
As has been mentioned in the comments you likely have a newline as the last character of your id field. The character (being invalid) is being replaced with a question mark.
Use this to remove the newline...
filename = "./"+id.chomp+".json"

How to get a file name from a list of files using link query

I am using linq query to get the filename from a list of file names. but I am getting null value. Is there anything wrong with the code??
var folderName = UserDetailsUtil.GetMemberPhotoPathFolderName(SessionData.UserID);
var fileName = SessionData.UserID;
var fileNames = Directory.GetFiles(Path.Combine(Server.MapPath("~/Content/Upload/MemberProfilePhotos/" + folderName)));
var actualFileName = fileNames.Where(x => x.StartsWith(fileName)).FirstOrDefault();
My image name will be with my userid. Total images in that particular folder comes into filenames. What i have to do is, I need to get the filename from the list of files
I assume that your file has an extension, so you need to find it without it, best by using the Path class:
var actualFileName = fileNames
.Where(fn => Path.GetFileNameWithoutExtension(fn) == fileName)
.FirstOrDefault();
Side-note acc. to "My image name will be with my userid". Then don't use StartsWith but ==, otherwise file 1 and 10 are equal. Changed that already in my code above.

Extract the filepath from this ruby string

I am using the ruby Dir method to get all the filenames within a directory. Like this:
dir_files = Dir["/Users/AM/Desktop/07/week1/dailies/regionals/*.csv"]
This gives me an array with each element listed below:
/Users/AM/Desktop/07/week1/dailies/regionals/ch002.csv
/Users/AM/Desktop/07/week1/dailies/regionals/ch014.csv
/Users/AM/Desktop/07/week1/dailies/regionals/ch90.csv
/Users/AM/Desktop/07/week1/dailies/regionals/ch112.csv
/Users/AM/Desktop/07/week1/dailies/regionals/ch234.csv
Im trying to extract just the part of the above strings that matches: "regionals/*.csv"
How do I do that in Ruby?
The following didn't work
#files_array.each do |f|
f = f.split("/").match(/*.csv/)
i = f.include?(".csv")
puts "#{i.inspect}"
#self.process_file(f[i])
end
Whats a clever way of doing this? I intend to pass the returned string of each filename to a helper method for processing. But as you can see all the csv files are located in a different directory as my executing script.
My script thats executing this is located at
/Users/AM/Desktop/07/week1/dailies/myScript.rb
Thanks
This will always post back the final directory and file name, regardless of the file pattern:
#files_array.map { |f| f.split("/")[-2..-1].join("/") }
#=> ["regionals/ch002.csv", "regionals/ch014.csv", "regionals/ch90.csv", "regionals/ch112.csv", "regionals/ch234.csv"]
This gives you the desired values :)
dir_files.map {|path| path[/regionals\/.*.csv/]}
#=> ["regionals/ch002.csv", "regionals/ch014.csv", "regionals/ch90.csv", "regionals/ch112.csv", "regionals/ch234.csv"]

Resources