I'm trying to read and print the contents of a text file, but nothing shows up:
coffee = open('coffeeInventory.txt' , 'r')
coffee.seek(0)
line = coffee.readline()
while line != '':
print(line)
coffee.close()
Thank you for any advice.
Try this:
with open('coffeeInventory.txt') as inf:
for line in inf:
print(line, end='')
readline leaves a newline on the end of the line, so use end='' to prevent print from appending its own newline.
Try this code for each line, please:
file = open('coffeeInventory.txt')
lines = file.readlines()
for line in lines:
print(line)
file.close()
Related
I think I've tried everything to make it work but I still can't get the results I want. I basically want to delete empty lines in txt file that my other script created. I've tried: .isspace(), deleting lines with n amount of spaces, deleting lines with '\n'. None of these worked can you guys help me? Here is part of txt file and my code:
Gmina Wiejska
Urząd Gminy Brzeziny
ul. Sienkiewicza 16a 95-060 Brzeziny
Łącko
Gmina Wiejska
Urząd Gminy Łącko
Łącko 445 33-390 Łącko
Węgliniec
Gmina Miejsko-wiejska
Urząd Gminy i Miasta Węgliniec
ul. Sikorskiego 3 59-940 Węgliniec```
code:
delete = ['<td align="center" class="top" colspan="3"><b>',
'</td>',
'<br/></b></td>',
'<br/></b>',
'None',
'brak',
'[]',
'\n'
]
with open('/Users/dominikgrzeskowiak/python/gminy/text/text1.txt','r+') as file:
for line in file:
print(a)
for i in delete:
line = line.replace(i,'')
print(i)
print(line)
if line != ' ' or line != ' \n' or line != ' ':
with open('/Users/dominikgrzeskowiak/python/gminy/text/text2.txt','a') as f:
f.write(line+'\n')
Just check if the line is not empty after removing blanks with strip
with open('text1.txt', 'r+', encoding='utf-8') as file, open('text2.txt', 'a', encoding='utf-8') as f:
for line in file:
if line.strip():
f.write(line)
You should open text2 once, not every line in the text1.
You could use regex for searching patterns
import re
with open('somefile.txt','r') as file:
txt = file.readlines()for i in txt:
if re.fullmatch("\\s*",i):
continue
print(i,end="")
but you could do it with pure python too
with open('somefile.txt','r') as file:
txt = file.readlines()
for i in txt:
if i.strip() == '':
continue
print(i, end='')
I am try to sort through the following file
Fantasy
Supernatural
Fantasy
UrbanFantasy
Fantasy
EpicFantasy
Fantasy
HighFantasy
I want to remove the word fantasy when it appears by itself and put the new list into another file
I tried
def getRidofFantasy():
file = open("FantasyGenres.txt", "r")
new_file = open("genres/fantasy", "w")
for line in file:
if line != "Fantasy":
new_file.write(line)
file.close()
new_file.close()
This does not work and I am at a lost as to why. The new file is the same as the old one. Can anyone explain what's happening and give an example of the correct solution?
Try this
with open('fantasy.txt') as f, open('generes/fantasy', 'w') as nf:
lines = [line+'\n' for line in f.read().splitlines() if line != "Fantasy"]
nf.writelines(lines)
In your code when you do for line in f the line variable also include the \n (endline) char, that's why it doesn't work.
Try this. -
def getRidofFantasy():
with open("FantasyGenres.txt", "r") as file:
content = [line.strip('\n') for line in file.readlines()]
new_list = list(filter(lambda a: a != 'Fantasy', content))
with open("genres/fantasy.txt", "w") as new_file:
[new_file.write(f'{line}\n') for line in new_list]
getRidofFantasy()
Similar to #Atin's answer, you can also do this:
with open('fantasy.txt') as f, open('generes/fantasy', 'w') as nf:
lines = [line for line in f.readlines() if line.strip() != "Fantasy"]
nf.writelines(lines)
That is because a new line is also a character:
Fantasy\n
Supernatural\n
etc.
You have to account for that. One possibility:
def getRidofFantasy():
with open("FantasyGenres.txt", "r") as f: # this way Python closes the file buffer for you
oldfile = f.readlines()
new_file = open("genres/fantasy", "w")
for line in oldfile:
line = line.rstrip('\n')
if line != "Fantasy":
new_file.write(line+'\n') # make sure to append the newline character again
new_file.close()
Okay so there is one thing you should know. When you read a line like that the variable will look something like this:-
line='Fantasy\n'
So, you need to strip that character. The simple solution without changing any of your code would be to just change the if statement. Change it to
if not 'Fantasy'== line.strip() and keep your code as it is and the new file that'll be generated will be the one you want.
i tried using the .strip() method which give me the line
f = open("myFile.txt")#this open myfile
for i in range(500): # print 500 character
line = f.readline().strip()
print(line)
my expected result is
"faowijfaoijfaoiwjfioawjfafawjfaoiwjfawofjafw"
You can do this.
with open("myFile.txt") as f:
chars_100 = f.read(100)
print (chars_100)
Can you help me identify what's wrong in this code? I want to put all the print output on the cmd to a txt file. This code only puts the last line.
import urllib.request
fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')
for line in fhand:
z = line.decode().strip()
with open('romeo.txt', 'w') as f:
print(z, file=f)
You are creating and writing 'romeo.txt' file for every line of the content. Swap the for loop and the opening file. Something like this:
import urllib.request
fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')
with open('romeo.txt', 'w') as f:
for line in fhand:
z = line.decode().strip()
print(z, file=f)
I'm trying to modify a specific line in a js file using python.
Here's the js file :
...
hide: [""]
...
Here's my python code :
with open('./config.js','r') as f:
lines = f.readlines()
with open('./config.js','w') as f:
for line in lines:
line = line.replace('hide', 'something')
f.write(line)
So it works but this is not what I want to do.
I want to write 'something' between the brackets and not replace 'hide'.
So I don't know how to do it: Do I have to replace the whole line or can I just add a word between the brackets?
Thanks
If you want to replace text at this exact line you could just do:
with open('./config.js','r') as f:
lines = f.readlines()
with open('./config.js','w') as f:
new_value = 'Something New'
for line in lines:
if line.startswith('hide'):
line = 'hide: ["{}"]'.format(new_value)
f.write(line)
or alternatively in the conditional
if line.startswith('hide'):
line = line.replace('""', '"Something new"')
Here's way to replace any value in brackets for hide that starts with any spacing.
lines = '''\
first line
hide: [""]
hide: ["something"]
last line\
'''
new_value = 'new value'
for line in lines.splitlines():
if line.strip().startswith('hide'):
line = line[:line.index('[')+2] + new_value + line[line.index(']')-1:]
print(line)
Output:
first line
hide: ["new value"]
hide: ["new value"]
last line
You can use fileinput and replace it inplace:
import fileinput
import sys
def replaceAll(file,searchExp,replaceExp):
for line in fileinput.input(file, inplace=1):
if searchExp in line:
line = line.replace(searchExp,replaceExp)
sys.stdout.write(line)
replaceAll("config.js",'hide: [""]','hide: ["something"]')
Reference
If hide: [""] is not ambiguous, you could simply load the whole file, replace and write it back:
newline = 'Something new'
with open('./config.js','r') as f:
txt = f.read()
txt = txt.replace('hide: [""]', 'hide: ["' + newline + '"]')
with open('./config.js','w') as f:
f.write(txt)
As long as you don't have "hide" anywhere else in the file, then you could just do
with open('/config.js','r') as f:
lines = f.readlines()
with open('./config.js','w') as f:
for line in lines:
line = line.replace('hide [""]', 'hide ["something"]')
f.write(line)
You can do this using re.sub()
import re
with open('./config.js','r') as f:
lines = f.readlines()
with open('./config.js','w') as f:
for line in lines:
line = re.sub(r'(\[")("\])', r'\1' + 'something' + r'\2', line)
f.write(line)
It works by searching for a regular expression, but forms a group out of what you want on the left ((\[")) and the right (("\])). You then concatenate these either side of the text you want to insert (in this example 'something').
The bounding ( ) makes a group which can be accessed in the replace with r'\1', then second group is r'\2'.