I want know how to delete a specific file line ?
example : file.txt
facebook
twitter
orkut
msn
Suppose I want to delete the line 3 then the file would be :
facebook
twitter
msn
I do not want to just delete the lines, need to organize and avoid getting empty lines in the file!
Load the file contents, manipulate them in memory, then write the new contents back to the file.
In this case you can load the file contents line by line using files.lines, store the ones you want in an array and leave out the ones you don't, then turn the array back into a string with table.concat.
You could look for a specific item by matching a string:
function func(file, toDelete)
local t = {}
local tt = {}
for line in io.lines(file) do
table.insert(t, line)
end
for c, r in pairs(t) do
if string.sub(r, 4) ~= toDelete then
table.insert(tt, string.sub(r, 4))
end
end
local nfile = io.open(file, "w+")
for a, b in pairs(tt) do
nfile:write(a .. ". " .. b .. "\n")
end
end
or by looking for the number:
function func(file, num)
local t = {}
local tt = {}
for line in io.lines(file) do
table.insert(t, line)
end
for c, r in pairs(t) do
if c ~= num then
table.insert(tt, string.sub(r, 4))
end
end
local nfile = io.open(file, "w+")
for a, b in pairs(tt) do
nfile:write(a .. ". " .. b .. "\n")
end
end
Carefull: this overrides the original file!
EDIT:
This is working for the example above, without the numbers in the front, you don't have to substitute the string.
Related
I have opened a file in Julia:
output_file = open(path_to_file, "a")
And I would like to chop the six last characters of the file.
I thought I could do it with chop, i.e., chop(output_file; tail = 6) but it seems it only works with String type and not with IOStream. How should I do?
julia> rbothpoly(0, 1, [5], 2, 30, "html")
ERROR: MethodError: no method matching chop(::IOStream; tail=6)
Closest candidates are:
chop(::AbstractString; head, tail) at strings/util.jl:164
Stacktrace:
[1]
[...] ERROR STACKTRACE [...]
[3] top-level scope at REPL[37]:1
I am new to IOStream, discovering them today.
In your case, because you're doing a single write to the end of the file and not doing any further read or other operations, you can also edit the file in-place like this:
function choppre(fname = "data/endinpre.html")
linetodelete = "</pre>\n"
linelength = length(linetodelete)
open(fname, "r+") do f
readuntil(f, linetodelete)
seek(f, position(f) - linelength)
write(f, " "^linelength)
end
end
This overwrites the text we wish to chop off with an equal length of space characters. I'm not sure if there's a way to simply delete the line (instead of overwriting it with ' ').
I have found what I wanted here, which adapts in my problem to:
(tmppath, tmpio) = mktemp()
open(output_filename, "r") do io
for line in eachline(io, keep=true) # keep so the new line isn't chomped
if line == "</pre>\n"
line = "\n"
end
write(tmpio, line)
end
end
close(tmpio)
mv(tmppath, output_filename, force=true)
chmod(output_filename, 0o777)
close(output_file)
Maybe my question could be marked as duplicate!
I'm trying to write code that will search the files in a directory and for any of them that contain a string of "51" thru "100" on the fifth line, it will print the file name.
I have tried modifying the first statement in the 'for' loop to:
s = i
for i in range(51,100):
but that just returns an error bc it's looking for a string, not an int
path = './data/'
files = [f for f in glob.glob(path + "*.crs", recursive=False)]
# Open the file
for f in files:
line = 5
fh: TextIO = open(f)
text = fh.read()
# Conditions
for line in f:
s: str = '62' # Takes input of a string from user
if s in text: # string is present in the text file
print(f)
break
else:
continue
fh.close()
TypeError: 'in <string>' requires string as left operand, not int
My current code will print out the name of the file containing '62' on the fifth line. I'm just looking for a way to make it print out all files that contain any number between 51 - 100 on the fifth line.
MAT Mathematics
Calculus I
TH 8/26/19 12/11/19
3
62
There's probably a more elegant way to do this, but this is what I came up with. Basically, for each file it opens the file and reads line by line until it gets to the line you want to check. Note that line 5 is the 6th line of the file because line numbers are offsets from 0. Then it checks the line for any numbers in numbersToCheck. I've used str(v) for v in range(51, 100) on the second line to convert integers into strings, which are then stored in numbersToCheck.
lineToCheck = 5
numbersToCheck = [str(v) for v in range(51, 100)] #convert integers to strings
path = './data/'
files = [f for f in glob.glob(path + "*.crs", recursive=False)]
for f in files:
fh = open(f) #open the file
for lineNo, line in enumerate(fh):
if lineNo == lineToCheck: #Once it gets to the correct line
if any(numberStr in line for numberStr in numbersToCheck): #Checks for numbers
print(line)
break #don'1t continue checking this file, move on to the next.
fh.close()
I have the following code to replace just one set of value from 26th line of 150 lines data. The problem is with the nested for loop. From the second iteration onwards, the inner loop isn't executing. Instead the loop skips to the last line
n= int(input("Enter the Number of values: "))
arr = []
print ('Enter the Fz values (in Newton): ')
for _ in range(n):
x=(input())
arr.append(x)
print ('Array: ', arr)
os.chdir ("D:\Work\python")
f = open("datanew.INP", "r+")
f1 = open("data.INP", "w+")
for i in range(len(arr)):
str2 = arr[i]
for j,line in enumerate(f):
if j == 25 :
new = line.split()
linenew = line.replace(new[1],str2)
print (linenew)
f1.write(linenew)
else:
f1.write(line)
print(arr[i], 'is replaced')
f.close()
f1.close()
The issue is that your code is looping over a file. On the first pass through, the end of file is reached. After that, there is no data left in the file to read, so the next loop has nothing to iterate over.
Instead, you might try reading over the whole file and storing the data in a list, then looping over that list. (Alternatively, you could eliminate the loops and access the 26th item directly.)
Here is some simple code to read from one file, replace the 26th line, and write to another file:
f = open("data.INP", "r") # Note that for simple reading you don't need the '+' added to the 'r'
the_data = f.readlines()
f.close()
the_data[25] = 'new data\n' # Remember that Python uses 0 indexing, thus the 25
f1 = open("updated_data.out", "w") # Assuming you want to write a new file, leave off the '+' here, as that indicates that you want to append to an existing file
for l in the_data:
f1.write(l)
f1.close()
Actually My file contents are.
ttsighser66
dagadfgadgadgfadg
dafgad
fgadfgad
ttsighser63
sadfsadf
asfdas
My code
file=open("C:\\file.txt","r")
cont = []
for i in file:
dd = i.strip("\n")
cont.append(dd)
cc = ",".join(cont)
if "tt" in i:
cc = ",".join(cont[:-1])
print(cont[-1], cc)
cont = []
My code generate below Output:
ttsighser66
ttsighser63 dagadfgadgadgfadg,dafgad,fgadfgad
But I want output like below format
ttsighser66,dagadfgadgadgfadg,dafgad,fgadfgad
ttsighser63,sadfsadf,asfdas
file=open("file.txt","r")
cont = []
for i in file:
dd = i.strip("\n")
cont.append(dd)
#print('cc',cont)
if "ttsighser" in i and len(cont) != 1:
cc = ",".join(cont[:-1])
print(cc)
cont = []
cont.append(dd)
print(",".join(cont))
If you don't need to store any strings to a list and just need to print strings, you could try this instead.
with open("file.txt", "r") as f:
line_counter = 0
file_lines = f.readlines()
for i in file_lines:
dd = i.strip()
if "tt" in dd:
print("{0}{1}".format("\n" if line_counter > 0 else "", dd), end="")
else:
print(",{0}".format(dd), end="")
line_counter += 1
print("")
The reason why your code displays
ttsighser66
ttsighser63 dagadfgadgadgfadg,dafgad,fgadfgad
instead of
ttsighser66,dagadfgadgadgfadg,dafgad,fgadfgad
ttsighser63,sadfsadf,asfdas
is because when you first encounter 'ttsighser66', it is appended to cont. Then since 'ttsighser66' contains 'tt', we would proceed to the conditional branch.
In the conditional branch, we would be joining the first and second to the last string in cont in cc = ",".join(cont[:-1]). However, since we only have 'ttsighser66' in cont, cont[:-1] will give us [] (an empty list). Since cont[:-1] is empty, ",".join(cont[:-1]) will be empty as well. Thus, cc will be empty. Since cc is empty, print(cont[-1], cc) will give us ttsighser66.
In the second line, ttsighser63 dagadfgadgadgfadg,dafgad,fgadfgad gets displayed because cont contains more than one value already so it will also display the values before 'ttsighser63'.
The remaining strings are not displayed because, based from your code, it would need another string containing 'tt' before the strings in cc could be displayed.
Essentially, you require a pair of strings containing 'tt' to display the strings between the pairs.
Additonal remark: The line cc = ",".join(cont) in your code seems pretty useless since its scope is limited to the for loop only and its value is being replaced inside the conditional branch.
version 1 (all data in list of strings && 1 time print)
fp=open("file.txt", "r")
data = []
for line in fp:
if "tt" in line:
data.append(line.strip())
else:
data.append(data.pop() + "," + line.strip())
fp.close()
[print (data) for line in data]
Version 2 (all data in a single string && 1 time print)
fp=open("file.txt","r")
data = ""
for line in fp:
if "tt" in line:
data += "\n" + line.strip()
else:
data += ","+line.strip()
fp.close()
data = data[1:]
print (data)
I have a string stored in sqlite database and I've assigned it to a var, e.g. string
string = "First line and string. This should be another string in a new line"
I want to split this string into two separated strings, the dot (.) must be replace with (\n) new line char
At the moment I'm stuck and any help would be great!!
for row in db:nrows("SELECT * FROM contents WHERE section='accounts'") do
tabledata[int] = string.gsub(row.contentName, "%.", "\n")
int = int+1
end
I tried the other questions posted here in stachoverflow but with zero luck
What about this solution:`
s = "First line and string. This should be another string in a new line"
a,b=s:match"([^.]*).(.*)"
print(a)
print(b)
Are you looking to actually split the string into two different string objects? If so maybe this can help. It's a function I wrote to add some additional functionality to the standard string library. You can use it as-is or rename it to what ever you like.
--[[
string.split (s, p)
====================================================================
Splits the string [s] into substrings wherever pattern [p] occurs.
Returns: a table of substrings or, if no match is made [nil].
--]]
string.split = function(s, p)
local temp = {}
local index = 0
local last_index = string.len(s)
while true do
local i, e = string.find(s, p, index)
if i and e then
local next_index = e + 1
local word_bound = i - 1
table.insert(temp, string.sub(s, index, word_bound))
index = next_index
else
if index > 0 and index <= last_index then
table.insert(temp, string.sub(s, index, last_index))
elseif index == 0 then
temp = nil
end
break
end
end
return temp
end
Using it is very simple, it returns a tables of strings.
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
> s = "First line and string. This should be another string in a new line"
> t = string.split(s, "%.")
> print(table.concat(t, "\n"))
First line and string
This should be another string in a new line
> print(table.maxn(t))
2