I am trying to get a to be the first line of the file and b to be the second.
This prints nothing.
f = open(filename)
line = f.readline().strip()
while line:
a = f.readline()
b = f.readline()
line = f.readline()
print(a)
print(b)
I want to assign specific lines to variables, not just read all of them.
Check the tutorial first please, it says:
If you want to read all the lines of a file in a list you can also use
list(f) or f.readlines().
lines = f.readlines()
a = lines[0]
b = lines[1]
lines =[]
with open(filename) as f:
i =0
for line in f:
lines[i] = line
i += 1
print '1st Line is: ', lines[0]
print '2st Line is: ', lines[1]
Related
I have to sort some elements in a text file that contains the names with the schedules of some teachers. Searching on google, I found this program:
def sorting(filename):
infile = open(filename)
words = []
for line in infile:
temp = line.split()
for i in temp:
words.append(i)
infile.close()
words.sort()
outfile = open("result.txt", "w")
for i in words:
outfile.writelines(i)
outfile.writelines(" ")
outfile.close()
sorting("file.txt")
The code works, but it sorts the elements of the file on a single line, while I want it to be written as in the file, but in alphabetical and numerical orders. To unterstand it, let's say I have this file:
c
a
b
What I want is to sort it like this:
a
b
c
but it sorts it like this:
a b c
I use python 3.10. Can anyone please help me? Thanks.
def sorting(filename):
infile = open(filename)
words = []
for line in infile:
temp = line.split()
for i in temp:
words.append(i)
infile.close()
words.sort()
outfile = open("result.txt", "w")
for i in words:
outfile.writelines(i)
outfile.writelines("\n") # edited Instead of ' ' write '\n'
outfile.close()
sorting("test.txt")
i would like to know how i could get all lines after the first in a python file
I've tried with this:
fr = open("numeri.txt", "r")
count = 0
while True:
line = fr.readline(count)
if line == "":
break
count += 1
print(line)
fr.close()
Could anyone help me? Thanks
You could add an extra if statement to check if count != 0 Since on the first loop it will be 0.
I don't know if i understood well, but to obtain all the lines skipping the first one you can simple do
lines = []
with open("numeri.txt") as fobj:
lines = fobj.readlines()[1:]
count = len(lines)+1 if lines else 0 # If you want to maintain the same counting as in your example
count = 0
with open(file, 'r') as file:
next(file.readline()) # skip the first line
for count, line in enumerate(file.readlines()): # read remaining lines with count
if not line: # If line equals "" this will be True
break
print(count, line)
count -= 1 # To ignore last lines count.
Just read the first line without using it:
with open('numeri.txt') as f:
f.readline()
lines = f.readlines()
print(*lines, sep='')
To ignore the first line you can also use next(f) (instead of f.readline()).
This is also fine:
with open('numeri.txt') as f:
lines = f.readlines()[1:]
print(*lines, sep='')
Try using l[1:]. It returns a subset of l that consist in the elements of l except the first position.
with open("numeri.txt", "r") as f:
content = f.readlines()[1:]
for line in content:
print(line.strip('\n')) # In order to avoid introduce double \n since print ends with a '\n'
EDIT: Based on #riccardo-bucco ' solution:
with open("numeri.txt", "r") as f:
content = f.readlines()[1:]
print(*content, sep='')
To print all but the first line:
with open('numeri.txt', 'r') as f:
output = ''.join(f.readlines()[1:])
print(output)
start count at 1 so it skips the first line
...
count = 1
...
Let's say I have a large text file, and I want to skip a line containing some keyword, as well as 2 lines after that line.
Original_file:
line1 some words
line2 some words
line3 keyword
line4 some words
line5 some words
line6 some words
line7 some words
line8 some words
New_file:
line1 some words
line2 some words
line6 some words
line7 some words
line8 some words
A simplified snippet of my code:
with open('Original_file','r') as f:
lines = f.readlines()
nf = open('New_file', 'w')
for line in lines:
if 'keyword' in line:
for i in range(3): continue
else:
nf.write(line + "\n")
The loop, "for i in range(3): continue" doesn't skip lines (I assume because it just continues within that nested for loop instead of the "for line in lines" for loop. I also tried "next(f)" instead of "continue" and got a StopIteration error message.
Of course, if I try,
with open('Original_file','r') as f:
lines = f.readlines()
nf = open('New_file', 'w')
for line in lines:
if 'keyword' in line:
continue
else:
nf.write(line + "\n")
it succeeds in skipping a line, but only the line with the keyword, whereas I want to skip the next two lines as well (a total of 3 lines).
Any suggestions are appreciated. Thank you for your help.
You can try iterate over indexes instead of elements:
with open('Original_file','r') as f:
lines = f.readlines()
nf = open('New_file', 'w')
i = 0
while i< len(lines):
line = lines[i]
if 'keyword' in line:
i+=3
else:
nf.write(line + "\n")
i+=1
Make a counter and skip lines based off that.
with open('Original_file','r') as f:
lines = f.readlines()
nf = open('New_file', 'w')
skip_lines = 0
for line in lines:
if skip_lines > 0:
skip_lines -= 1
elif 'keyword' in line:
skip_lines = 3
else:
nf.write(line + "\n")
You can achieve this with a flag /counter
with open('Original_file','r') as f:
lines = f.readlines()
skip = 0
nf = open('New_file', 'w')
for line in lines:
if skip:
skip -=1
elif 'keyword' in line:
skip = 3
else:
nf.write(line + "\n")
The problem is that you extract lines directly from a list and because of that, you have no possible interaction with the underlying iterator used by for line in lines.
You should simply use the file object as an iterator:
with open('Original_file','r') as f, open('New_file', 'w') as nf
for line in f:
if 'keyword' in line:
for i in range(2): next(f)
else:
nf.write(line)
The only assumption here is that any line containing keyword is followed with at least 2 other lines.
You can use next(), i.e.:
with open("old.txt") as f, open("new.txt", "w") as w:
for line in f:
if "keyword" in line:
next(f), next(f)
continue
w.write(line)
Demo
If you prefer a list comprehension, you can also use:
with open("old.txt") as f, open("new.txt", "w") as w:
[w.write(line) if not "keyword" in line else [next(f) for _ in range(2)] for line in f]
Demo
I want to open a file, and read the first 10 lines of a file. If a file has less than 10 lines it should read as many lines as it has. Each line has to be numbered, wether it's text or it's whitespace. Because I have to strip each line, I can't differentiate between an empty string, and the end of a file. For example if I read a file with only three lines, it will print out lines 1 - 10, with lines 4 - 10 being empty, but I would like to have it stop after reaching that 3rd line, as that would be the end of the file. I would really appreciate any help, thank you.
def get_file_name():
fileName = input('Input File Name: ')
return fileName
def top(fileName):
try:
file = open(fileName, 'r')
line = 'text'
cnt = 1
while cnt <= 10:
if line != '':
line = file.readline()
line = line.rstrip('\n')
print(str(cnt) + '.', line)
cnt += 1
else:
line = file.readline()
line = line.rstrip('\n')
print(str(cnt) + '.', line)
cnt += 1
file.close()
except IOError:
print('FILE NOT FOUND ERROR:', fileName)
def main():
fileName = get_file_name()
top(fileName)
main()
def read_lines():
f = open("file-name.txt","r")
num = 1
for line in f:
if num > 10:
break
print("LINE NO.",num, ":",line)
num = num + 1
f.close()
Here, the loop exits at the end of the file. So if you only had 7 lines, it will exit automatically after the 7th line.
However, if you have 10 or more than 10 lines then the "num" variable takes care of that.
EDIT: I have edited the print statement to include the line count as well and started the line count with 1.
with open(filename, 'r') as f:
cnt = 1
for line in f:
if cnt <= 10:
print(str(cnt) + '.', line, end='')
cnt += 1
else:
break
This should do exactly what you need. You can always remove the if/else and then it will read exactly however many lines are in the file. Example:
with open(filename, 'r') as f:
cnt = 1
for line in f:
print(str(cnt) + '.', line, end='')
cnt += 1
You can try to load all the lines into array, count the total line and use an if statement to check if total is 10 or not, then finally use a for loop like for i in range (0,9): to print the lines.
The code i am using is selecting the highest number out of three in a text file set out as
R 3 5 7
F 2 9 6
I 6 3 5
When it is run it does wright the correct infomation to the text file but comes up with
max_in_line = max(nums)
ValueError: max() arg is an empty sequence
my code is
with open (classno, 'r') as f, open("class11.txt", 'w') as fout:
for line in f.readlines(): #does right swaps around
if not line.strip(): continue
parts = line.split()
nums_str = line.split()[1:]
nums = [int(n) for n in nums_str]
max_in_line = max(nums)
print (max_in_line)
print (line)
score = (max_in_line)#same problem
name = (parts[0])
fout.write(("\n") + str(score) + (" ") + (name))
fout.close
f.close#it does write them but comes up with the problem
Try this code, just skip the empty line or empty element in the list:
with open ('classno.txt', 'r') as f, open("class11.txt", 'w') as fout:
lines = [line.strip() for line in f]
for line in lines:
splitted = [i for i in line.split(' ') if i]
nums = splitted[1:]
max_nums = max(map(int, nums))
name = splitted[0]
fout.write('\n' + str(max_nums) + ' ' + name)
It works for me, hope helps.