How to read a file line by line in crystal language? - crystal-lang

Hi I want to read a file line by line with crystal language, but I don't know how can I do that.
I read crystal documentation, but I couldn't find my answer.
It's my code:
system("ls /etc/NetworkManager/system-connections/ > Fox.txt")
file = File.read("Fox.txt")
system("sudo cat /etc/NetworkManager/system-connections/\'#{file}\' >> Fox_done.txt")

To read a file line by line, you can use File#each_line:
File.each_line("/path/to/input.txt") do |line|
puts line
end
If the file is small and you want to load all lines in memory, you can also use File#read_lines:
File.read_lines("/path/to/input.txt") # returns a Array(String)

Related

Read file by removing the unwanted lines using python pandas

I am reading a file which contains json data and in between it contains other text.So for that i want to check that condition on reading the file if line starts with condition how can i achieve this?
with open ("inputfile.txt") as f:
content = f.read().replace('}U','},')[::-1].replace(',', '', 1)].replace(":[",":").replace("]","")
content = '[{}]'.format(content)
data=json.loads(content)
I want to check the file if the line starts with condition like this
startswith("{"+"\"M\""+":")
I Have tried reading line by line and checking if the line startswith condition but for large files it is tak
inputfile.txt
sometext
{"M":{"1":"data","2":"data2"}}U
asdklaasd
{"M":{"3":"555","5":"3333"}}U
I want to read the lines only that start with {"M":
Output I need is like this
[{"M":{"1":"data","2":"data2"}},{"M":{"3":"555","5":"3333"}}]

Writing in files

I have been trying to write onto a file while using python but for some reason it keeps writing onto my console and not my created file. Yes I know this question has been asked before and yes i have used the .close() command. Here is my block of code.
myfile= open ('C:/Users/12345/Documents/Grouped_data.txt','r')
with open ('C:/Users/12345/nanostring.txt','w') as output:
for line in myfile:
Templist= line.split()
print line
print Templist[0], Templist[4], Templist[5],Templist[6], Templist[7], Templist[8], Templist[9], Templist[10], Templist[12]
print output
myfile.close()
output.close()
This should be as simple as:
>>> with open('somefile.txt', 'a') as the_file:
... the_file.write('Hello\n')
From The Documentation:
Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single '\n' instead, on all platforms.
In python 2.7,
You can use >> after the print and use as name
So here it is print>>output,line
myfile= open ('C:/Users/12345/Documents/Grouped_data.txt','r')
with open ('C:/Users/12345/nanostring.txt','w') as output:
for line in myfile:
Templist= line.split()
print>>output,line # Note the changes
print>>output,Templist[0], Templist[4], Templist[5],Templist[6], Templist[7], Templist[8], Templist[9], Templist[10], Templist[12] # Note the changes
Note: print directly prints in terminal and print>>as name, prints to file.

Python: only run command once in for loop

I have a for loop which creates a CSV of values of several files in a directory.
Within this loop I only want to create the file and write in the header once, currently I am doing this:
#name&path to table file
test = tablefile+"/"+str(cell[:-10])+"_Table.csv"
#write file
if not os.path.isfile(test):
csv.writer(open(test, "wt"))
with open(test, 'w') as output:
wr = csv.writer(output, lineterminator=',')
for val in header_note:
wr.writerow([val])
and to append data I have:
with open(test, 'a') as output:
wr = csv.writer(output, lineterminator=',')
for val in table_all:
wr.writerow([val])
Which works well, however, when I run the script over again another time it will append more data to the bottom of that same .csv. What I want is for the first time through the for-loop, is to just overwrite any existing .csv with a new one with a header then continue on appending data, and overwrite/re-write header once the script is run again. Thanks!
It look like you may have some code problems other than file handling, but here goes: You problem is basically that opening a file in 'w' mode will overwrite everything in the file, and opening in 'a' mode will not allow you to change the header line.
To get around this, you will have to get the contents of the file (if it already exists), then overwrite the file, including those lines that where there to begin with.
You will want something along the lines of:
if os.path.exists(file_name): # if file already exists
with open(file_name, 'r') as in_file: # open it
old_lines = in_file.readlines()[1:] # read all lines from file EXCEPT header line
with open(file_name, 'w') as out_file: # open file again, with 'w' to create/overwrite
out_file.write(new_header_line) # write new header line to file
for line in old_lines:
out_file.write(line) # write all preexisting lines back into file
# continue writing whatever you want.

LPTHW Ex 16, imy ssues with my own script

I successfully completed ex16 in LPTHW and now I'm trying to replicate it in my own script to better understand the lesson. I typed the following but the shell returns with:
File "bruce.py", line 23, in
scribble.truncate()
I0Error: File not open for writing
My script is as follows:
from sys import argv
script, file_name=argv
scribble=open(file_name)
print "Master Bruce, here is your file: %s" % file_name
print scribble.read()
print """
Master Bruce, to change the contents of the file
simply press ENTER and type three lines:
"""
line1=raw_input("line 1:")
line2=raw_input("line 2:")
line3=raw_input("line 3:")
print "Just a few seconds Master Bruce..."
scribble.truncate()
scribble.write(line1,line2,line3)
scribble.close
My understanding is that the file was opened in line 5 already. I also tried scibble.open() on line 22 but that didnt work either. Your help is appreciated.
It means exactly what it says: the file isn't open for writing. You opened it in read-only mode.
scribble=open(file_name)
is equivalent to
scribble=open(file_name, "r")
You need to open the file in read/write mode. Since you don't want to truncate it at the start and don't want to append to it, use r+.
scribble=open(file_name, "r+")
You should brush up on the documentation for open() here.
Incidentally, you should also look into opening files with the with keyword here for cleaner handling.
with open(file_name, "r+") as scribble:
# do things
...
The most commonly-used values of mode are 'r' for reading [...]. If mode is omitted, it defaults to 'r'.
[...]
Modes 'r+', 'w+' and 'a+' open the file for updating (reading and writing); note that 'w+' truncates the file.
source

Formatting text file in Python

I want to format an existing text file, the contents of text file are:
Aurangabad
Adilabad
Beed
I want to format it like:
Aurangabad|Aurangabad,
Adilabad|Adilabad,
Beed|Beed,
I am not so good in Python file handling.
the code to do so:
with open('file_name.txt','r') as file:
list_of_lines = file.readlines()
new_lines_list = []
for line in list_of_lines:
line = line.replace('\n','') #because each line end with this and we don't need it now (\n is the newline chr)
new_lines_list.append('{0}|{0}\n'.format(line)) #the same as - new_lines_list.append(line+'|'+line+'\n')
with open('file_name.txt','w') as file:
string_to_write = ''.join(new_lines_list)
file.write(string_to_write)
if you don't understand the with statement: it is basically to open the file and at the end it will close itself (and even if some exception occur it will still close (I explain bad if you don't understand go here)