I only want to get the second result, which num prints and use it.
savee1 is a .txt file
def copycoordinates():
savee1 = filedialog.askopenfilename(initialdir="C:/USERS/" + username + "/documents/Euro Truck Simulator 2/profiles", title="Choose FIRST File", filetypes=[("sii files", "*.sii")])
savee2 = filedialog.askopenfilename(initialdir="C:/USERS/" + username + "/documents/Euro Truck Simulator 2/profiles", title="Choose SECOND File", filetypes=[("sii files", "*.sii")])
i1 = Label(frame5, text="Chosen FIRST File \n" + savee1)
i1.pack()
i2 = Label(frame5, text="Chosen SECOND File \n" + savee2)
i2.pack()
command=lambda:[save1()]
subprocess.Popen(["C:/SII_Decrypt.exe", savee1])
command=lambda:[save2()]
subprocess.Popen(["C:/SII_Decrypt.exe", savee2])
#time.sleep(1)
with open(savee1, "r+") as save1:
for num, line in enumerate(save1, 1):
if "truck_placement:" in line:
print(num)
If you mean you want the second match, you can try:
with open(savee1, "r+") as save1:
match = 0
for num, line in enumerate(save1, 1):
if 'truck_placement:' in line:
match += 1
if match == 2
print(num)
else:
continue
The num will print on the second match.
There are definitely better ways, but this is one of the most easy solution.
results = list()
with open(savee1, "r+") as save1:
for num, line in enumerate(save1, 1):
if "truck_placement:" in line:
print(num)
results.append(num)
print(results[1]) #this is the value you want
not sure what's in your text file, but usually things are separated in some way (line break, tab separated, comma separated). You should split on what ever it is that separates and then you can just index the resulting list. the following code assumes the things you want are separated by new lines:
with open(save1, "r+") as infile:
f=infile.read()
list_o_txt = f.split('\n')
print (list_o_txt[1])
if you want to make a sublist of texts that only contain a phrase 'truck_placement'
with open(save1,'r') as infile:
f=infile.read()
list_o_txt = f.split('\n') # produces a list
filtered_list = [line for line in list_o_txt if 'truck_placement' in line] #filters the list
print (filtered_list[1]) #prints the second item
Related
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
...
I'm given a text file called input1.txt1 this file contains the following
aspiration
classified
federation
graduation
millennium
philosophy
quadratics
transcript
wilderness
zoologists
Write a program that first reads in the name of an input file, followed by two strings representing the lower and upper bounds of a search range. The file should be read using the file.readlines() method. The input file contains a list of alphabetical, ten-letter strings, each on a separate line. Your program should output all strings from the list that are within that range (inclusive of the bounds).
EX:
Enter the path and name of the input file: input1.txt
Enter the first word: ammunition
Enter the second word (it must come alphabetically after the first word): millennium
The words between ammunition and millennium are:
aspiration
classified
federation
graduation
millennium
file_to_open = input()
bound1 = input()
bound2 = input()
with open(file_to_open) as file_handle:
list1 = [line.strip() for line in file_handle]
out = [x for x in list1 if x >= bound1 and x <= bound2]
out.sort()
print('\n'.join(map(str, out)))
Use a list comprehension with inequalities to check the string range:
out = [x for x in your_list if x >= 'ammunition' and x <= 'millennium']
This assumes that your range is inclusive on both ends, that is, you want to include ammunition and millennium on both ends of the range.
To further sort the out list and then write to a file, use:
out.sort()
f = open('output.txt', 'w')
text = '\n'.join(out)
f.write(text)
f.close()
if you should use readline() try this :
filepath = 'Iliad.txt'
start = 'sometxtstart'
end = 'sometxtend'
apending = False
out = ""
with open(filepath) as fp:
line = fp.readline()
while line:
txt = line.strip()
if(txt == end):
apending = False
if(apending):
out+=txt + '\n'
if(txt == start):
apending = True
line = fp.readline()
print(out)
This worked for me:
file = input()
first = input()
second = input()
with open(file) as f:
lines = f.readlines()
for line in lines:
l = line.strip('\n')
if (l >= first) and (l <= second):
print(line.strip())
else:
pass
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.
I'm trying to insert an increment after the occurance of ~||~ in my .txt. I have this working, however I want to split it up, so after each semicolon, it starts back over at 1.
So Far I have the following, which does everything except split up at semicolons.
inputfile = "output2.txt"
outputfile = "/output3.txt"
f = open(inputfile, "r")
words = f.read().split('~||~')
f.close()
count = 1
for i in range(len(words)):
if ';' in words [i]:
count = 1
words[i] += "~||~" + str(count)
count = count + 1
f2 = open(outputfile, "w")
f2.write("".join(words))
Why not first split the file based on the semicolon, then in each segment count the occurences of '~||~'.
import re
count = 0
with open(inputfile) as f:
semicolon_separated_chunks = f.read().split(';')
count = len(re.findall('~||~', semicolon_separated_chunks))
# if file text is 'hello there ~||~ what is that; what ~||~ do you ~|| mean; nevermind ~||~'
# then count = 4
Instead of resetting the counter the way you are now, you could do the initial split on ;, and then split the substrings on ~||~. You'd have to store your words another way, since you're no longer doing words = f.read().split('~||~'), but it's safer to make an entirely new list anyway.
inputfile = "output2.txt"
outputfile = "/output3.txt"
all_words = []
f = open(inputfile, "r")
lines = f.read().split(';')
f.close()
for line in lines:
count = 1
words = line.split('~||~')
for word in words:
all_words.append(word + "~||~" + str(count))
count += 1
f2 = open(outputfile, "w")
f2.write("".join(all_words))
See if this works for you. You also may want to put some strategically-placed newlines in there, to make the output more readable.
Hello everyone i have an issue with this problem, the problem is i need to reset the count after every line in the file, i put a comment so you can see where i want to reset the count.
The program is suppose to cut each line after every specified lineLength.
def insert_newlines(string, afterEvery_char):
lines = []
for i in range(0, len(string), afterEvery_char):
lines.append(string[i:i+afterEvery_char])
string[:afterEvery_char] #i want to reset here to the beginning of every line to start count over
print('\n'.join(lines))
def main():
filename = input("Please enter the name of the file to be used: ")
openFile = open(filename, 'r')
file = openFile.read()
lineLength = int(input("enter a number between 10 & 20: "))
while (lineLength < 10) or (lineLength > 20) :
print("Invalid input, please try again...")
lineLength = int(input("enter a number between 10 & 20: "))
print("\nYour file contains the following text: \n" + file + "\n\n") # Prints original File to screen
print("Here is your output formated to a max of", lineLength, "characters per line: ")
insert_newlines(file, lineLength)
main()
Ex. If a file has 3 lines like this with each line having 20 chars
andhsytghfydhtbcndhg
andhsytghfydhtbcndhg
andhsytghfydhtbcndhg
after the lines are cut it should look like this
andhsytghfydhtb
cndhg
andhsytghfydhtb
cndhg
andhsytghfydhtb
cndhg
i want to RESET the count after every line in the file.
I'm not sure I understand your problem, but from your comments it appears you simply want to cut the input string (file) to lines lineLength long. That is already done in your insert_newlines(), no need for the line with comment there.
However, if you want to output lines meaning strings ending with newline char that should be no more than lineLength long, then you could simply read the file like this:
lines = []
while True:
line = openFile.readline(lineLength)
if not line:
break
if line[-1] != '\n':
line += '\n'
lines.append(line)
print(''.join(lines))
or alternatively:
lines = []
while True:
line = openFile.readline(lineLength)
if not line:
break
lines.append(line.rstrip('\n'))
print('\n'.join(lines))
I don't understand the issue here, the code seems to work just fine:
def insert_newlines(string, afterEvery_char):
lines = []
# if len(string) is 100 and afterEvery_char is 10
# then i will be equal to 0, 10, 20, ... 90
# in lines we'll have [string[0:10], ..., string[90:100]] (ie the entire string)
for i in range(0, len(string), afterEvery_char):
lines.append(string[i:i+afterEvery_char])
# resetting i here won't have any effect whatsoever
print('\n'.join(lines))
>>> insert_newlines('Beautiful is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex.\n..', 10)
Beautiful
is better
than ugly.
Explicit
is better
than impli
cit.
Simpl
e is bette
r than com
plex.
..
isn't that what you want?