Suppose I have a file like this:
words
words
3245, 3445,
345634, 345678
I am wondering if it is possible to add data onto the 4th line of the code so the out put is this:
words
words
3245, 3445, 67899
345634, 345678
I found a similar tutorial: appending a data in a specific line of a text file in Python?
but the problem is I don't want to use .startswith because the files will all have different beginnings.
Thanks for your help!
You can achieve that by doing this
# define a function so you can re-use it for writing to other specific lines
def writetoendofline(lines, line_no, append_txt):
lines[line_no] = lines[line_no].replace('\n', '') + append_txt + '\n'
# open the file in read mode to read the current input to memory
with open('./text', 'r') as txtfile:
lines = txtfile.readlines()
# in your case, write to line number 4 (remember, index is 3 for 4th line)
writetoendofline(lines, 3, ' 67899')
# write the edited content back to the file
with open('./text', 'w') as txtfile:
txtfile.writelines(lines)
# close the file
txtfile.close()
Related
My text.txt looks like this
abcd
xyzv
dead-hosts
-abcd.srini.com
-asdsfcd.srini.com
And I want to insert few lines after "dead-hosts" line, I made a script to add lines to file, there is extra space before last line, that's mandatory in my file, but post added new lines that space got removed, dont know how to maintain the space as it is.
Here is my script
Failvrlist = ['srini.com','srini1.com']
tmplst = []
with open(‘test.txt’,'r+') as fd:
for line in fd:
tmplst.append(line.strip())
pos = tmplst.index('dead-hosts:')
tmplst.insert(pos+1,"#extra comment ")
for i in range(len(Failvrlist)):
tmplst.insert(pos+2+i," - "+Failvrlist[i])
tmplst.insert(pos+len(Failvrlist)+2,"\n")
for i in xrange(len(tmplst)):
fd.write("%s\n" %(tmplst[i]))
output is as below
abcd
xyzv
dead-hosts
#extra comment
- srini.com
- srini1.com
- abcd.srini.com
- asdsfcd.srini.com
if you look at the last two lines the space got removed, please advise .
Points:
In you code , pos = tmplst.index('dead-hosts:'), you are trying to find dead-hosts:. However, input file you have given has only "dead hosts". No colon after dead-hosts, I am considering dead-hosts:
While reading file first time into list, use rstrip() instead of strip(). Using rstrip() will keep spaces at the start of line as it is.
Once you read file into list, code after that should be outside with block which is use to open and read file.
Actually, flow of code should be
Open file and read lines to list and close the file.
Modify list by inserting values at specific index.
Write the file again.
Code:
Failvrlist = ['srini.com','srini1.com']
tmplst = []
#Open file and read it
with open('result.txt','r+') as fd:
for line in fd:
tmplst.append(line.rstrip())
#Modify list
pos = tmplst.index('dead-hosts:')
tmplst.insert(pos+1,"#extra comment")
pos = tmplst.index('#extra comment')
a = 1
for i in Failvrlist:
to_add = " -" + i
tmplst.insert(pos+a,to_add)
a+=1
#Write to file
with open('result.txt','w') as fd:
for i in range(len(tmplst)):
fd.write("%s\n" %(tmplst[i]))
Content of result.txt:
abcd
xyzv
dead-hosts:
#extra comment
-srini.com
-srini1.com
-abcd.srini.com
-asdsfcd.srini.com
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')
I am very new with python. I have a .txt file and want to convert it to a .csv file with the format I was told but could not manage to accomplish. a hand can be useful for it. I am going to explain it with screenshots.
I have a txt file with the name of bip.txt. and the data inside of it is like this
I want to convert it to csv like this csv file
So far, what I could do is only writing all the data from text file with this code:
read_files = glob.glob("C:/Users/Emrehana1/Desktop/bip.txt")
with open("C:/Users/Emrehana1/Desktop/Test_Result_Report.csv", "w") as outfile:
for f in read_files:
with open(f, "r") as infile:
outfile.write(infile.read())
So is there a solution to convert it to a csv file in the format I desire? I hope I have explained it clearly.
There's no need to use the glob module if you only have one file and you already know its name. You can just open it. It would have been helpful to quote your data as text, since as an image someone wanting to help you can't just copy and paste your input data.
For each entry in the input file you will have to read multiple lines to collect together the information you need to create an entry in the output file.
One way is to loop over the lines of input until you find one that begins with "test:", then get the next line in the file using next() to create the entry:
The following code will produce the split you need - creating the csv file can be done with the standard library module, and is left as an exercise. I used a different file name, as you can see.
with open("/tmp/blip.txt") as f:
for line in f:
if line.startswith("test:"):
test_name = line.strip().split(None, 1)[1]
result = next(f)
if not result.startswith("outcome:"):
raise ValueError("Test name not followed by outcome for test "+test_name)
outcome = result.strip().split(None, 1)[1]
print test_name, outcome
You do not use the glob function to open a file, it searches for file names matching a pattern. you could open up the file bip.txt then read each line and put the value into an array then when all of the values have been found join them with a new line and a comma and write to a csv file, like this:
# set the csv column headers
values = [["test", "outcome"]]
current_row = []
with open("bip.txt", "r") as f:
for line in f:
# when a blank line is found, append the row
if line == "\n" and current_row != []:
values.append(current_row)
current_row = []
if ":" in line:
# get the value after the semicolon
value = line[line.index(":")+1:].strip()
current_row.append(value)
# append the final row to the list
values.append(current_row)
# join the columns with a comma and the rows with a new line
csv_result = ""
for row in values:
csv_result += ",".join(row) + "\n"
# output the csv data to a file
with open("Test_Result_Report.csv", "w") as f:
f.write(csv_result)
I'm writing a piglatin converter in Python that takes a txt file and translates it line by line and outputs to another textfile in piglatin. It works properly except when I'm reading multiple lines, I need to have it output exactly the same.
code that splits the file between spaces
def getWords(vowels, file):
listOfW = file.read().split()
return listOfW
text inside notepad file:
if beast student
away
Converted: ['ifway', 'eastbay', 'tudentsay', 'awayway']
current output: (should be on two lines)
ifway eastbay tudentsay awayway
What it should look like:
ifway eastbay tudentsay
awayway
getWords is just a function I used to get a list and then I convert them with another function
thanks for any help!
Assuming you already have such a function:
def convertToPigLatin(word):
# returns converted string
You can open both your reading and writing file. Then iterate over each line of the in-file, split the line on whitespace, and convert each word in a list comprehension. Then you can write out that line to the out-file.
with open(infile, 'r') as fIn, open(outfile, 'w') as fOut:
for line in fIn:
convertedWords = [convertToPigLatin(word) for word in line.split()]
fOut.write(' '.join(convertedWords) + '\n')
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