Printing all sets in list python - python

fob=open('c:/Users/username/Desktop/CE151 Python/ass2/grid.txt','r')
text_file = open("grid.txt","r")
for item in fob:
tuple(item.split(';')[0:])
print(item[0:])
I have loaded a text file and I am trying put each line into a list.When I can for the first line it prints only 1 line. Even when i call for all lines it still outputs 1 line. How do I print a line i request for.
grid.txt contains:
paghzkctudptjdphsztprhttl
sbsnakjwqbouftmgnjqbtlinu
tsewohvobdsduqjiffkyylodo
oukwwefroyamapmlrrpvdolop
cqkfxtlksjvtmtrsbycmqrrri
kfervlqidqaxaoanfqjlmcpjh
yoyywrbpfcjlfbcbbcoecspwl
twbxetyuyufvvmauawjmbwlqh
txokdexmdbtgvhpsvsqtmljdx
dcatenrehteoxqdgeueljtrrn
jarteqvtxejfsqddkbuhcysfq
hpdrowssapxtrxhpdxcdhicon

fob=open('c:/Users/username/Desktop/CE151 Python/ass2/grid.txt','r')
text_file = open("grid.txt","r")
listy=[]
for elem in text_file.read().split('\n'):
listy.append(elem)
text_file.close()
You could try this. The lines are stored in the list listy.

Related

Read file names from text file and print to list using python

I want to read a text file which contains list of file names and append that to a list.
I have written the code, but the output is repeated twice.
For example, there is text file named filelist.txt which contains the list of files (ex:- mango.txt).
When I run the code its printing mango.txt twice.
def im_ru(filelist1):
with open(filelist1,"r") as fp:
lines = fp.read().splitlines()
for line in lines:
print(lines)
Print line instead
for line in lines:
print(line)
It's a one-liner:
from pathlib import Path
filenames = Path("filelist.txt").read_text().splitlines()
You error is to print lines instead of line in your for loop
Use:
def im_ru(filelist1):
with open(filelist1, 'r') as fp:
# You have to remove manually the end line character
lines = [line.strip() for line in fp]
return lines
Usage:
>>> im_ru('data.txt')
['mango.txt', 'hello.csv']
Content of data.txt:
mango.txt
hello.csv

Open and Read a CSV File without libraries

I have the following problem. I am supposed to open a CSV file (its an excel table) and read it without using any library.
I tried already a lot and have now the first row in a tuple and this in a list. But only the first line. The header. But no other row.
This is what I have so far.
with open(path, 'r+') as file:
results=[]
text = file.readline()
while text != '':
for line in text.split('\n'):
a=line.split(',')
b=tuple(a)
results.append(b)
return results
The output should: be every line in a tuple and all the tuples in a list.
My question is now, how can I read the other lines in python?
I am really sorry, I am new to programming all together and so I have a real hard time finding my mistake.
Thank you very much in advance for helping me out!
This problem was many times on Stackoverflow so you should find working code.
But much better is to use module csv for this.
You have wrong indentation and you use return results after reading first line so it exits function and it never try read other lines.
But after changing this there are still other problems so it still will not read next lines.
You use readline() so you read only first line and your loop will works all time with the same line - and maybe it will never ends because you never set text = ''
You should use read() to get all text which later you split to lines using split("\n") or you could use readlines() to get all lines as list and then you don't need split(). OR you can use for line in file: In all situations you don't need while
def read_csv(path):
with open(path, 'r+') as file:
results = []
text = file.read()
for line in text.split('\n'):
items = line.split(',')
results.append(tuple(items))
# after for-loop
return results
def read_csv(path):
with open(path, 'r+') as file:
results = []
lines = file.readlines()
for line in lines:
line = line.rstrip('\n') # remove `\n` at the end of line
items = line.split(',')
results.append(tuple(items))
# after for-loop
return results
def read_csv(path):
with open(path, 'r+') as file:
results = []
for line in file:
line = line.rstrip('\n') # remove `\n` at the end of line
items = line.split(',')
results.append(tuple(items))
# after for-loop
return results
All this version will not work correctly if you will '\n' or , inside item which shouldn't be treated as end of row or as separtor between items. These items will be in " " which also can make problem to remove them. All these problem you can resolve using standard module csv.
Your code is pretty well and you are near goal:
with open(path, 'r+') as file:
results=[]
text = file.read()
#while text != '':
for line in text.split('\n'):
a=line.split(',')
b=tuple(a)
results.append(b)
return results
Your Code:
with open(path, 'r+') as file:
results=[]
text = file.readline()
while text != '':
for line in text.split('\n'):
a=line.split(',')
b=tuple(a)
results.append(b)
return results
So enjoy learning :)
One caveat is that the csv may not end with a blank line as this would result in an ugly tuple at the end of the list like ('',) (Which looks like a smiley)
To prevent this you have to check for empty lines: if line != '': after the for will do the trick.

Python Loop Only Parses First Five Lines of Text File

I'm attempting to read and print a .txt file line-by-line in Python using the readline function. The below code is intended to print out the entire text file line-by-line, but as of right now, it only prints out the first five lines of the text file.
filename = input("Enter the name and extension of the file you want to open.")
file = open(filename, "r")
fileline = file.readline()
for line in fileline:
fileline = fileline.rstrip("\n")
print(fileline)
fileline = file.readline()
file.close()
I expect the code to print out the entire file line by line, but it currently only prints out the first five lines. What is the bug in the code?
This line:
for line in fileline:
is looping through the characters of fileline, which contains the first line of the file. So if the first line has 5 characters, this loop will execute 5 times.
Then inside the loop, you print the line and then read the next line into the fileline variable. That has no effect on the loop, which is still iterating over the characters in the first line.
To make the program deliberately print the first 5 lines, you can do:
for i in range(5):
fileline = file.readline()
if (fileline == ''): #end of file reached
break
print(fileline.rtrim('\n'))
Or you can iterate over file, which automatically reads lines, and use a separate counter variable
i = 0
for line in file:
print(line.rtrim('\n'))
i += 1
if i == 5:
break

Writing a line of row per iteration to file without overwriting the file in python

I have searched this on Stackoverflow and all of the "duplicates" for this topic but it seems remained unanswered. I have tried all these:
Attempt#1:
for word in header:
writer.writerow([word]
Pasted from writing data from a python list to csv row-wise
Attempt#2:
And this one, should have been close but it has a bug:
# Open a file in witre mode
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name
Pasted from <http://www.tutorialspoint.com/python/file_writelines.htm>
# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line
seq = ["This is 6th line\n", "This is 7th line"]
# Write sequence of lines at the end of the file.
fo.seek(0, 2)
line = fo.writelines( seq )
# Now read complete file from beginning.
fo.seek(0,0)
for index in range(7):
line = fo.next()
print "Line No %d - %s" % (index, line)
# Close opend file
fo.close()
Pasted from http://www.tutorialspoint.com/python/file_writelines.htm
Attempt#3:
>>>outF = open("myOutFile.txt", "w")
>>>for line in textList:
...    outF.write(line)
...    outF.write("\n")
>>>outF.close()
Pasted from http://cmdlinetips.com/2012/09/three-ways-to-write-text-to-a-file-in-python/
Attempt#4:
with open('file_to_write', 'w') as f:
f.write('file contents')
Pasted from Correct way to write line to file in Python
Attempt#5:
This one which uses the append when writing to file.. but it appends each line at the end of each row. So it would be hard for me to separate all the rows.
append_text = str(alldates)
with open('my_file.txt', 'a') as lead:
lead.write(append_text)
Pasted from Python: Saving a string to file without overwriting file's contents
Can someone help me how to write a newline of row per iteration in a loop to a file without overwriting the file?
data = [1,2,3,4,5]
with open('asd.txt', 'w') as fn:
for i in data:
fn.write(str(i) + '\n') # Add a \n (newline) so the next write will occure in the next line
Content of asd.txt:
1
2
3
4
5
If you want to append to a file use with open('asd.txt', 'a') as fn:
There is 2 ways to do that:
First by adding '\n' character at the end of your output line :
for x in row:
writer.write(x + "\n")
Second by opening file in Append mode, it is going to add lines existing text file but be careful.it's not overwrite the file :
fw = open(myfile.txt,'a')

how to Use python to find a line number in a document and insert data underneath it

Hi I already have the search function sorted out:
def searchconfig():
config1 = open("config.php", "r")
b='//cats'
for num, line in enumerate(config1,0):
if b in line:
connum = num + 1
return connum
config1.close()
This will return the line number of //cats, I then need to take the data underneath it put it in a tempoary document, append new data under the //cats and then append the data in the tempoary document to the original? how would i do this? i know that i would have to use 'a' instead of 'r' when opening the document but i do not know how to utilise the line number.
I think, the easiest way would be to read the whole file into a list of strings, work on that list and write it back afterwards.
# Read all lines of the file into a list of strings
with open("config.php", "r") as file:
lines = list(file)
file.close()
# This gets the line number for the first line containing '//cats'
# Note that it will throw an StopIteration exception, if no such line exists...
linenum = (num for (num, line) in enumerate(lines) if '//cats' in line).next()
# insert a line after the line containing '//cats'
lines.insert(linenum+1, 'This is a new line...')
# You could also replace the line following '//cats' like
lines[linenum+1] = 'New line content...'
# Write back the file (in fact this creates a new file with new content)
# Note that you need to append the line delimiter '\n' to every line explicitely
with open("config.php", "w") as file:
file.writelines(line + '\n' for line in lines)
file.close()
Using "a" as mode for open would only let you append ath the end of the file.
You could use "r+" for a combined read/write mode, but then you could only overwrite some parts of the file, there is no simple way to insert new lines in the middle of the file using this mode.
You could do it like this. I am creating a new file in this example as it is usually safer.
with open('my_file.php') as my_php_file:
add_new_content = ['%sNEWCONTENT' %line if '//cat' in line
else line.strip('\n')
for line in my_php_file.readlines()]
with open('my_new_file.php', 'w+') as my_new_php_file:
for line in add_new_content:
print>>my_new_php_file, line

Categories