reading text line by line in python 3.6 - python-3.x

I have date.txt file where are codes
ex:
1111111111111111
2222222222222222
3333333333333333
4444444444444444
I want to check each code in website.
i tried:
with open('date.txt', 'r') as f:
data = f.readlines()
for line in data:
words = line.split()
send_keys(words)
But this copy only last line to.
I need to make a loop that will be checking line by line until check all
thanks for help
4am is to late 4my little brain..
==
edit:
slove
while lines > 0:
lines = lines - 1
with open('date.txt', 'r') as f:
data = f.readlines()
words = data[lines]
print(words)

Try this I think it will work :
line_1 = file.readline()
line_2 = file.readline()
repeat this for how many lines you would like to read.
One thing to keep in mind is if you print these lines they will all print on the same line.

Related

Merge only if two consecutives lines startwith at python and write the rest of text normally

Input
02000|42163,54|
03100|4|6070,00
03110|||6070,00|00|00|
00000|31751150201912001|01072000600074639|
02000|288465,76|
03100|11|9060,00
03110|||1299,00|00|
03110||||7761,00|00|
03100|29|14031,21
03110|||14031,21|00|
00000|31757328201912001|01072000601021393|
Code
prev = ''
with open('out.txt') as f:
for line in f:
if prev.startswith('03110') and line.startswith('03110'):
print(prev.strip()+ '|03100|XX|PARCELA|' + line)
prev = line
Hi, I have this code that search if two consecutives lines startswith 03110 and print those line, but I wanna transforme the code so it prints or write at .txt also the rest of the lines
Output should be like this
02000|42163,54|
03100|4|6070,00
03110|||6070,00|00|00|
00000|31751150201912001|01072000600074639|
02000|288465,76|
03100|11|9060,00
03110|||1299,00|00|3100|XX|PARCELA|03110||||7761,00|00|
03100|29|14031,21
03110|||14031,21|00|
00000|31757328201912001|01072000601021393|
I´m know that I´m getting only those two lines merged, because that is the command at print()
03110|||1299,00|00|3100|XX|PARCELA|03110||||7761,00|00|
But I don´t know to make the desire output, can anyone help me with my code?
# I assume the input is in a text file:
with open('myFile.txt', 'r') as my_file:
splited_line = [line.rstrip().split('|') for line in my_file] # this will split every line as a separate list
new_list = []
for i in range(len(splited_line)):
try:
if splited_line[i][0] == '03110' and splited_line[i-1][0] == '03110': # if the current line and the previous line start with 03110
first = '|'.join(splited_line[i-1])
second = '|'.join(splited_line[i])
newLine = first + "|03100|XX|PARCELA|"+ second
new_list.append(newLine)
elif splited_line[i][0] == '03110' and splited_line[i+1][0] == '03110': # to escape duplicating in the list
pass
else:
line = '|'.join(splited_line[i])
new_list.append(line)
except IndexError:
pass
# To write the new_list to text files
with open('new_file' , 'a') as f:
for item in new_list:
print(item)
f.write(item + '\n')

How to edit a line in a notepad file using python

I am trying to edit a specific line of a notepad file using Python 3. I can read from any part of the file and write to the end of it, however whenever I have tried editing a specific line, I am given the error message 'TypeError: 'int' object is not subscriptable'. Does anybody know how I could fix this?
#(This was my first attempt)
f = open('NotepadTester.txt', 'w')
Edit = input('Enter corrected data')
Line = int(input('Which line do you want to edit?'))
f.write(Edit)[Line-1]
f.close()
main()
#(This was my second attempt)
f = open('NotepadTester.txt', 'w')
Line = int(input('Which line do you want to edit?'))
Edit = input('Enter corrected data')
f[Line-1] = (Edit)
main()
you can't directly 'edit' a line in a text file as far as I know. what you could do is read the source file src to a variable data line-by-line, edit the respective line and write the edited variable to another file (or overwrite the input file) dst.
EX:
# load information
with open(src, 'r') as fobj:
data = fobj.readlines() # list with one element for each text file line
# replace line with some new info at index ix
data[ix] = 'some new info\n'
# write updated information
with open(dst, 'w') as fobj:
fobj.writelines(data)
...or nice and short (thanks to Aivar Paalberg for the suggestion), overwriting the input file (using open with r+):
with open(src, 'r+') as fobj:
data = fobj.readlines()
data[ix] = 'some new info\n'
fobj.seek(0) # reset file pointer...
fobj.writelines(data)
You should probably load all the lines into memory first, modify it from there, and then write the whole thing to a file.
f = open('NotepadTester.txt', 'r')
lines = f.readlines()
f.close()
Which_Line = int(input('Which line do you want to edit? '))
Edit = input('Enter corrected data: ')
f = open("NotepadTester.txt",'w')
for i,line in enumerate(lines):
if i == Which_Line:
f.writelines(str(Edit)+"\n")
else:
f.writelines(line)
f.close()

How to delete digits-only lines from a text file?

Let's say I have a text file which contains both alphanumerical values and only numerical values of length 10 digits line by line, like the one shown below:
abcdefgh
0123456789
edf6543jewjew
9876543219
I want to delete all the lines which contains only those random 10 digit numbers, i.e. expected output for the above example is the following:
abcdefgh
edf6543jewjew
How can one do this in Python 3.x?
with open("yourTextFile.txt", "r") as f:
lines = f.readlines()
with open("yourTextFile.txt", "w") as f:
for line in lines:
if not line.strip('\n').isnumeric():
f.write(line)
elif len(line.strip('\n')) != 10:
f.write(line)
Open the input file, read all its lines, filter out the lines that contain only digits, then write the filtered lines back to a new file.
import re
with open(input_file_path) as file:
lines = file.readlines()
output_lines = [line for line in lines if not re.match(r'^[0-9]+$', line.strip('\n'))]
with open(output_file_path, 'w') as file:
file.write('\n'.join(output_lines))
import re
fh=open('Desktop\Python13.txt','r+')
content=fh.readlines()
fh.seek(0)
for line in content:
if re.match(r'[0-9]{10}',line):
content.remove(line)
fh.write(''.join(content))
fh.truncate()
fh.close()

file reading in python, need help for homework

Write a function func(infilepath) that reads the file whose file path is infilepath, and prints the number of times each character(excluding newline characters) appeared in the file, in sorted order of the characters.
Any help would be greatly appreciated !
This won't be the exact answer, but enough to get you started!
First, open a file:
f = open("file.txt", "r")
Then read lines
lines = f.readlines()
Define a dictionary. Split the line by spaces, increment the dictionary by one if they character is already present in the dictionary, else initialize it to 0.
chars = {}
lines = [line.strip() for line in lines]
for line in lines:
line = line.split(" ")
for i in line:
if i not in chars.keys():
chars[i] = 0
else:
chars[i]+=1
More about file handling: https://github.com/thewhitetulip/build-app-with-python-antitextbook/blob/master/manuscript/06-file-handling.md
More about sets/lits/dictionaries: https://github.com/thewhitetulip/build-app-with-python-antitextbook/blob/master/manuscript/04-list-set-dict.md
Some practical examples to get you thinking: https://github.com/thewhitetulip/build-app-with-python-antitextbook/blob/master/manuscript/13-examples.md

How to print a file containing a list

So basically i have a list in a file and i only want to print the line containing an A
Here is a small part of the list
E5341,21/09/2015,C102,440,E,0
E5342,21/09/2015,C103,290,A,290
E5343,21/09/2015,C104,730,N,0
E5344,22/09/2015,C105,180,A,180
E5345,22/09/2015,C106,815,A,400
So i only want to print the line containing A
Sorry im still new at python,
i gave a try using one "print" to print the whole line but ended up failing guess i will always suck at python
You just have to:
open file
read lines
for each line, split at ","
for each line, if the 5th part of the splitted str is equal to "A", print line
Code:
filepath = 'file.txt'
with open(filepath, 'r') as f:
lines = f.readlines()
for line in lines:
if line.split(',')[4] == "A":
print(line)

Resources