I am reading an external txt file and displaying all the lines which has field 6 as Y. I then need to count these lines. However, when I add the sum function it will only print 1 of the lines, if I remove this sum function all the lines display as expected. I am presuming its something to do with the for loop but can't seem figure out how to get all lines to display and keep my sum. Can anyone help me spot where this is going wrong?
noLines = 0
fileOpen = open ("file.txt","r")
print ("Name: " + "\tDate: " + "\tAge: " + "\tColour: " + "\tPet")
for line in fileOpen:
line = line[:-1]
field = line.split(',')
if field[6] == "Y":
print()
print (field[0] +"\t\t" + field[1] + "\t" + field[2] + "\t\t" + field[3] + "\t\t" + field[4])
noLines = sum(1 for line in fileOpen)
print ()
print(noLines)
You are using sum incorrectly. In order to achieve the desired result, you may replace your current code with sum as:
noLines = sum(1 for l in open("file.txt","r") if l[:-1].split(',')[6]=='Y')
Issue with current code: Because fileOpen is a generator. You are exhausting it completely within sum and hence your next for iteration is not happening. Instead of using sum, you may initialize noLines before the for loop as:
noLines = 0
for line in fileOpen:
# your stuff ...
And instead of sum, do:
noLines += 1
# instead of: noLines = sum(1 for line in fileOpen)
Related
I want a text file that has every variation of xxxxx-xxxxx (x is a number)
so I want to create a text file that goes
00000-00000
00000-00001
00000-00002
00000-00003
etc...
how can I do that with python?
The trick is to use .zfill(n) if you want to append "n" zeros before some integers. So, if you have i = 1 but you want to print it like 00001, you can you the following code:
print(str(i).zfill(5))
And as to your question, the solution is:
with open("output.txt", "a") as f:
for i in range(100000):
for j in range(100000):
my_str = str(i).zfill(5) + "-" + str(j).zfill(5) + "\n"
f.write(my_str)
f.close()
Note: This will take a while to complete.
You can do it using a nested loop like this:
pattern = '00000-00000'
stack = []
for i in range(100000):
for j in range(100000):
num = pattern[:5-len(str(i))]+str(i) + pattern[5] + pattern[6:-len(str(j))]+str(j)
stack.append(num)
***Just don't run this code. It will break your computer.
Try this.
lst = []
s = '0000000000'
for a in range(10000):
l = list(s + str(a))[-10:]
l.insert(4,'-')
lst.append(''.join(l)+'\n')
with open('name.txt','w') as file:
file.writelines(lst)
I'm trying to make my program return the exact same string but with ** between each character. Here's my code.
def separate(st):
total = " "
n = len(st + st[-1])
for i in range(n):
total = str(total) + str(i) + str("**")
return total
x = separate("12abc3")
print(x)
This should return:
1**2**a**b**c**3**
However, I'm getting 0**1**2**3**4**5**6**.
You can join the characters in the string together with "**" as the separator (this works because strings are basically lists in Python). To get the additional "**" at the end, just concatenate.
Here's an example:
def separate(st):
return "**".join(st) + "**"
Sample:
x = separate("12abc3")
print(x) # "1**2**a**b**c**3**"
A note on your posted code:
The reason you get the output you do is because you loop using for i in range(n): so the iteration variable i will be each index in st. Then when you call str(total) + str(i) + str("**"), you cast i to a string, and i was just each index (from 0 to n-1) in st.
To fix that you could iterate over the characters in st directly, like this:
for c in st:
or use the index i to get the character at each position in st, like this:
for i in range(len(st)):
total = total + st[i] + "**"
welcome to StackOverflow!
I will explain part of your code line by line.
for i in range(n) since you are only providing 1 parameter (which is for the stopping point), this will loop starting from n = 0, 1, 2, ... , n-1
total = str(total) + str(i) + str("**") this add i (which is the current number of iteration - 1) and ** to the current total string. Hence, which it is adding those numbers sequentially to the result.
What you should do instead is total = str(total) + st[i] + str("**") so that it will add each character of st one by one
In addition, you could initialize n as n = len(st)
so -----2-----3----5----2----3----- would become -----4-----5----7----4----5-----
if the constant was 2 and etc. for every individual line in the text file.
This would involve splitting recognising numbers in between strings and adding a constant to them e.g ---15--- becomes ---17--- not ---35---.
(basically getting a guitar tab and adding a constant to every fret number)
Thanks. Realised this started out vague and confusing so sorry about that.
lets say the file is:
-2--3--5---7--1/n-6---3--5-1---5
and im adding 2, it should become:
-4--5--7---9--3/n-8---5--7-3---7
Change the filename to something relevant and this code will work. Anything below new_string needs to be change for what you need, eg writing to a file.
def addXToAllNum(int: delta, str: line):
values = [x for x in s.split('-') if x.isdigit()]
values = [str(int(x) + delta) for x in values]
return '--'.join(values)
new_string = '' # change this section to save to new file
for line in open('tabfile.txt', 'r'):
new_string += addXToAllNum(delta, line) + '\n'
## general principle
s = '-4--5--7---9--3 -8---5--7-3---7'
addXToAllNum(2, s) #6--7--9--11--10--7--9--5--9
This takes all numbers and increments by the shift regardless of the type of separating characters.
import re
shift = 2
numStr = "---1----9---15---"
print("Input: " + numStr)
resStr = ""
m = re.search("[0-9]+", numStr)
while (m):
resStr += numStr[:m.start(0)]
resStr += str(int(m.group(0)) + shift)
numStr = numStr[m.end(0):]
m = re.search("[0-9]+", numStr)
resStr += numStr
print("Result:" + resStr)
Hi You Can use that to betwine every line in text file add -
rt = ''
f = open('a.txt','r')
app = f.readlines()
for i in app:
rt+=str(i)+'-'
print " ".join(rt.split())
import re
c = 2 # in this example, the increment constant value is 2
with open ('<your file path here>', 'r+') as file:
new_content = re.sub (r'\d+', lambda m : str (int (m.group (0)) + c), file.read ())
file.seek (0)
file.write (new_content)
I have a list that is composed of nested lists, each nested list contains two values - a float value (file creation date), and a string (a name of the file).
For example:
n_List = [[201609070736L, 'GOPR5478.MP4'], [201609070753L, 'GP015478.MP4'],[201609070811L, 'GP025478.MP4']]
The nested list is already sorted in order of ascending values (creation dates). I am trying to use a While loop to calculate the difference between each sequential float value.
For Example: 201609070753 - 201609070736 = 17
The goal is to use the time difference values as the basis for grouping the files.
The problem I am having is that when the count reaches the last value for len(n_List) it throws an IndexError because count+1 is out of range.
IndexError: list index out of range
I can't figure out how to work around this error. no matter what i try the count is always of range when it reaches the last value in the list.
Here is the While loop I've been using.
count = 0
while count <= len(n_List):
full_path = source_folder + "/" + n_List[count][1]
time_dif = n_List[count+1][0] - n_List[count][0]
if time_dif < 100:
f_List.write(full_path + "\n")
count = count + 1
else:
f_List.write(full_path + "\n")
f_List.close()
f_List = open(source_folder + 'GoPro' + '_' + str(count) + '.txt', 'w')
f_List.write(full_path + "\n")
count = count + 1
PS. The only work around I can think of is to assume that the last value will always be appended to the final group of files. so, when the count reaches len(n_List - 1), I skip the time dif calculation, and just automatically add that final value to the last group. While this will probably work most of the time, I can see edge cases where the final value in the list may need to go in a separate group.
I think using zip could be easier to get difference.
res1,res2 = [],[]
for i,j in zip(n_List,n_List[1:]):
target = res1 if j[0]-i[0] < 100 else res2
target.append(i[1])
n_list(len(n_list)) will always return an index out of range error
while count < len(n_List):
should be enough because you are starting count at 0, not 1.
FYI, here is the solution I used, thanks to #galaxyman for the help.
I handled the issue of the last value in the nested list, by simply
adding that value after the loop completes. Don't know if that's the most
elegant way to do it, but it works.
(note: i'm only posting the function related to the zip method suggested in the previous posts).
def list_zip(get_gp_list):
ffmpeg_list = open(output_path + '\\' + gp_List[0][1][0:8] + '.txt', 'a')
for a,b in zip(gp_List,gp_List[1:]):
full_path = gopro_folder + '\\' + a[1]
time_dif = b[0]-a[0]
if time_dif < 100:
ffmpeg_list.write("file " + full_path + "\n")
else:
ffmpeg_list.write("file " + full_path + "\n")
ffmpeg_list.close()
ffmpeg_list = open(output_path + '\\' + b[1][0:8] + '.txt', 'a')
last_val = gp_List[-1][1]
ffmpeg_list.write("file " + gopro_folder + '\\' + last_val + "\n")
ffmpeg_list.close()
all. I'm having trouble outputting new lines to a txt file. The output is good but it's all in one line. Any ideas on how to work around?
#Double numberer
end=100
count=0
count=int(input("What number would you like to start?"))
end=int(input("What number would you like to end?"))
biglist = []
logfile=open("output.txt", mode="w", encoding="utf-8")
while count < end+1:
logfile.write(str(count),"\n")
logfile.write(str(count),"\n")
print(count)
count += 1
print("done")
logfile.close()
To concatenate the new lines to the string, use a + symbol:
logfile.write(str(count) + "\n")
logfile.write(str(count) + "\n")
Also, be aware that your while loop incrementing count each time is unnecessary in Python. You could just do this:
for x in range(0, end + 1):
logfile.write((str(x) + "\n") * 2)
print(x)
One simple way is:
print(string, file=theFileYouOpened)