How to get first letter of each line in python? - python

here is what I got txt and open
txt file looks like
f = open('data.txt', 'r')
print(f.read())
the show['Cat\n','Dog\n','Cat\n','Dog\n'........]
output
But I would like to get this
['C\n','D\n','C\n','D\n'........]

First you'll want to open the file in read mode (r flag in open), then you can iterate through the file object with a for loop to read each line one at a time. Lastly, you want to access the first element of each line at index 0 to get the first letter.
first_letters = []
with open('data.txt', 'r') as f:
for line in f:
first_letters.append(line[0])
print(first_letters)
If you want to have the newline character still present in the string you can modify line 5 from above to:
first_letters.append(line[0] + '\n')

f = open("data.txt", "r")
for x in f:
print(x[0])
f.close()

Related

How can append a string to every number on a text file?

I have a phone number list,each on a new line and I want to append a string “#ctest.com” to the end of every new line.
with open(“demofile.txt”, “r”) as f1:
Lines = f1.readlines()
For x in Lines:
f= open(“demofile.txt”, “a”)
f.writelines([“#vtest.com”])
f.close()
y = open(“demofile.txt”, “r”)
Print(Y.read())
I was expecting each line to print as below
7163737373#vtest.com
7156373737#vtest.com
For all the files on new lines.
But I got this
7163737373
7156373737#vtest.com,vtest.com
You're not appending to each line, you're just appending #vtestcom to the end of the file each time through the loop.
You need to reopen the file in write mode, not append mode, and write each x from the original readlines().
with open("demofile.txt", "r") as f1:
lines = f1.readlines()
with open("demofile.txt", "w") as f:
for line in lines:
f.write(f'{line.strip()}#ctest.com\n')
with open("demofile.txt", "r") as y:
print(y.read())
FYI, this is much easier to do in bash:
sed -i 's/$/#vtest.com' demofile.txt

skip 2 lines after a match while reading from a file

I am trying to code something where I first look for some string in a line in a txt file and when it is found I want to skip that row and the row below to get a new txt file without those rows. I really didn't get any solution from other questions here so maybe this will work
My code looks like this now:
with open("bla.txt", "r+") as f
new_f = f.readlines()
f.seek(0)
for line in new_f:
if "abc" not in line:
f.write(line)
else:
pass
pass
f.truncate()
I tried it with next(f) aswell but it didn't work for me. thanks in advance
This code creates a new file that skip the current and next row if the current row has the string ABC:
with open('bla.txt','r') as f:
text = f.read()
lines = text.split('\n')
with open('new_file.txt','w') as nf:
l = 0
while l<(len(lines)):
if 'ABC' in lines[l]:
l = l+2
else:
nf.write(lines[l]+'\n')
l = l+1
Try something simple like this:
import os
search_for = 'abc'
with open('input.txt') as f, open('output.txt', 'w') as o:
for line in f:
if search_for in line:
next(f) # we need to skip the next line
# since we are already processing
# the line with the string
# in effect, it skips two lines
else:
o.write(line)
os.rename('output.txt', 'input.txt')
Here is a repl with sample code.

How to remove line that contain a certain string in python

I have a text file that looks like this
Big:house
small:door
Big:car
Small:chair
Big:plane
How to I remove the lines that contain the word "big" so it may look like this, I dont want to create a new file all together though
small:door
small:chair
Here was my attempt
with open('QWAS.txt','r') as oldfile:
for line in oldfile:
if bad_words in line:
newfile.write(line)
This is what we can do:
Read data to string (remove rows that start with 'big')
Go to the start of file (seek)
Write the string
Truncate (remove overflow)
And now to the code, open it in read and write mode:
with open('QWAS.txt','r+') as f:
data = ''.join([i for i in f if not i.lower().startswith('big')]) #1
f.seek(0) #2
f.write(data) #3
f.truncate() #4
Try this:
newfile = r'output.txt'
oldfile = r'input.txt'
with open(newfile, 'w') as outfile, open(oldfile, 'r') as infile:
for line in infile:
if if line[:5].lower() == 'small':
outfile.write(line)
#output
small:door
Small:chair
Of course, this assumes you want to eliminate rows where small or Small is to the left of the colon. Additionally, you will have a new file output, as I don't think you really want to update your input file.
You can try using regular expressions
import re
oldfile = open('QWAS.txt','r')
newfile = open('newfile.txt','w')
for line in oldfile:
if re.search('[Ss]mall',line):
newfile.write(line)
oldfile.close()
newfile.close()
Which gives the output file "newfile.txt"
small:door
Small:chair
If you just take every line that doesn't have small and write it to a new file "newfile2.txt"
import re
oldfile = open('QWAS.txt','r')
newfile = open('newfile.txt','w')
newfile2 = open('newfile2.txt','w')
for line in oldfile:
if re.search('[Ss]mall',line):
newfile.write(line)
else:
newfile2.write(line)
oldfile.close()
newfile.close()
newfile2.close()

Write the first word/letter of each line to a new file

I have a file 'master.sql' that contains:
a.b.c
d.e.f
g.h.i
and I want to write on 'databases.sql' just the first letters, like this:
a
d
g
Here is my code, but returns just the last letter, the 'g'.
with open ('master.sql', 'r') as f:
for line in f:
x=(line.split('.')[0])
with open('databases.sql', 'w') as f:
f.write(str(x))
How can I fix this?
You'll need to write your data as you read it, otherwise you're not going to be able to do what you want. Fortunately, with allows you to open multiple files concurrently. This should work for you.
with open ('master.sql', 'r') as f1, open('databases.sql', 'w') as f2:
for line in f1:
f2.write(line.split('.')[0] + '\n')
Don't forget to write a newline, because file.write doesn't add one automatically.
Using list:
x = []
with open('master.sql', 'r') as f:
for line in f.readlines():
x.append(line.split('.')[0])
with open('databases.sql', 'w') as f:
for word in x:
f.write(str(word)+'\n')
The variable x receives all values, but each loop overwrite the last value. Hence, the result is 'g'.
To save all values you can do like this:
lst = []
with open ('master.sql', 'r') as f:
for line in f:
lst.append(line.split('.')[0])
x = '\n'.join(lst)
with open('databases.sql', 'w') as f:
f.write(x)

Search, delete and output to a newly created file

I wish to create a function that will search each line of a input file, search through each line of this file looking for a particular string sequence and if it finds it, delete the whole line from the input file and output this line into a newly created text file with a similar format.
The input files format is always like so:
Firstname:DOB
Firstname:DOB
Firstname:DOB
Firstname:DOB
etc...
I want it so this file is input, then search for the DOB (19111991) and if it finds this string in the line then delete it from the input file and finally dump it into a new .txt document .
I'm pretty clueless if I'm being honest but I guess this would be my logically attempt even though some of the code may be wrong:
def snipper(iFile)
with open(iFile, "a") as iFile:
lines = iFile.readlines()
for line in lines:
string = line.split(':')
if string[1] == "19111991":
iFile.strip_line()
with open("newfile.txt", "w") as oFile:
iFile.write(string[0] + ':' + '19 November' + '\n')
Any help would be great.
Try this code instead:
def snipper(filename)
with open(filename, "r") as f:
lines = f.readlines()
new_data = filter(lambda x: "19111991" in x, lines)
remaining_old_data = filter(lambda x: "19111991" not in x, lines)
with open("newfile.txt", "w") as oFile:
for line in new_data:
oFile.write(line.replace("19111991", "19th November 1991'"))
with open(filename, "w") as iFile:
for line in remaining_old_data:
iFile.write(line)

Categories