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)
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 have 5 input files. I'm reading the targets & arrays from the 2nd & 3rd lines. I have 2sum function. I need to output the function's returned value(s) and output them to 5 output files.
I know my functions correct. I print it out just fine.
I know I'm reading 5 input files & creating & writing to 5 output files.
What I can't figure out is how to write my return value(s) from the twoSum function INTO the output function.
def twoSum(arr, target):
for i in range(len(arr)):
for j in range(i, len(arr)):
curr = arr[i] + arr[j]
if arr[i]*2 == target:
return [i, i]
return answer
if curr == target:
return [i, j]
Read 5 files
inPrefix = "in"
outPrefix = "out"
for i in range(1, 6):
inFile = inPrefix + str(i) + ".txt"
with open(inFile, 'r') as f:
fileLines = f.readlines()
target = fileLines[1]
arr = fileLines[2]
how do i get write twoSum's value to output file?
???????
Output to 5 files
outFile = outPrefix + str(i) + ".txt"
with open(outFile, 'a') as f:
f.write(target) #just a test to make sure I'm writing successfully
f.write(arr) #just a test to make sure I'm writing successfully
Two things that come to mind:
open the file in wt mode (Write Text).
processedOutput appears to be a list. When you write to a file, you need write a string. Are you wanting a CSV style output of those values ? or just a line of spaced out values ? The simplest way here, would be something like: " ".join(processedOutput). That will separate all the items in your processedOut list by a string.
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 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)
I have written the following code to write a file, convert it into integer values, save that file and then read and convert it back to the original string. However, it prints the output twice.
My code is
def write():
sentence=input('What is your Statement?:')
name=input('Name your file:')
sentence=sentence.lower()
words=sentence.split(' ')
file_register=set()
F_output=[]
position=[]
for i in words:
if i not in file_register:
F_output.append(i)
file_register.add(i)
for x in words:
for y in range(len(F_output)):
if x==F_output[y]:
position.append(y)
name+='.txt'
with open(str(name),'w') as f:
f.write(str(len(position)) + '\n')
for c in range(len(position)):
f.write(str(position[c]) + '\n')
f.write(str(len(F_output)) + '\n')
for d in range(len(F_output)):
f.write(str(F_output[d] + '\n'))
f.close
global name
global position
def read1():
savefile=[]
output=('')
with open(name,'r') as file_open:
num=int(file_open.readline())
while num!=0:
a1=file_open.readline()
a1_split=a1.split('\n')
position.append(int(a1_split[0]))
num-=1
file_integer=int(file_open.readline())
while file_integer!=0:
word_s=file_open.readline()
word_split=word_s.split()
savefile.append(word_split)
file_integer-=1
for n in range(len(position)):
a=position[n]
output+=str(savefile[a])+('')
global output
write()
read1()
print('Your file is: '+output)
I have tried searching, but I cannot find an answer for it. I am fairly new to Python and any help is appreciated.
In write(), you declare position as global. In read1(), you don't declare it as global, but since you never create a local position variable it's the global one that gets used. So you end up populating it twice: once in write() then once again in read1().
To make a long story short: dont use globals. You don't need them.
Also, you'd find your code way easier to read, understand and debug by 1/ using better naming, 2/ writing simple, short functions that do one single thing, works on their inputs (arguments) and return values (the same arguments should produce the same output values), and 3/ properly using python's for loop.
Here's an example of what your code could looks like following those rules:
def parse(sentence):
sentence=sentence.lower()
words=sentence.split(' ')
register=set()
output = []
positions = []
for word in words:
if word not in register:
output.append(word)
register.add(word)
for word in words:
for index in range(len(output)):
if word == output[index]:
positions.append(index)
return output, positions
def write(path, output, positions):
with open(path, 'w') as f:
f.write(str(len(positions)) + '\n')
for index in positions:
f.write(str(index) + '\n')
f.write(str(len(output)) + '\n')
for word in output:
f.write(word + '\n')
def read(path):
words = []
positions = []
with open(path, 'r') as f:
poscount = int(f.readline().strip())
while poscount:
line = f.readline().strip()
pos = int(line)
positions.append(pos)
poscount -= 1
wordcount = int(f.readline().strip())
while wordcount:
line = f.readline()
word = line.strip()
words.append(word)
wordcount -= 1
output = []
for index in positions:
word = words[index]
output.append(word)
return output, positions
def main():
sentence = input('What is your Statement?:')
path = input('Name your file:')
if not path.endswith(".txt"):
path +=".txt"
source_out, source_positions = parse(sentence)
write(path, source_out, source_positions)
read_out, read_positions = read(path)
print("your file is: {}".format(read_out))
if __name__ == "__main__":
main()
This code is still overly complicated IMHO but at least it's mostly readable, doesn't use any global, and should be easier to test.