Create a function for add_new_field in Python - python

I am trying to create a function for a task I mentioned earlier for adding a new field to some files that are stored in one folder. I read about the function method in Python and followed but it does not work. I would be happy if someone could guide me about it.
def newfield(infile,outfile):
infile.readlines()
outfile = ["%s\t%s" %(item.strip(),2) for item in infile]
outfile.write("\n".join(output))
outfile.close()
return outfile
and then I try to call it:
a = open("E:/SAGA/data/2006last/test/325145404.all","r")
b = open("E:/SAGA/data/2006last/test/325145404_edit.all","w")
newfield(a,b)
Moreover, when we create a function, should we call it in a same python shell or we can same it as a file and then call it?

Looks like the problem is you're assigning the list you build to the same name as the output file. You're also reading all of the lines out of the file and not assigning the result anywhere, so when your list comprehension iterates over it, it's already at the end of the file. So you can drop the readlines line.
def newfield(infile,outfile):
output = ["%s\t%s" %(item.strip(),2) for item in infile]
outfile.write("\n".join(output))
outfile.close()
return outfile

The line infile.readlines() consumes the whole input file. All lines are read and forgotten because they are not assigned to a variable.
The construct ["%s\t%s" %(item.strip(),2) for item in infile] is a list comprehension. This expression returns a list. By assigning it to the variable outfile the old value of outfile - probably a file object - is forgotten and replaced by the list returned by the list comprehension. This list object does not have a write method. By assigning the list to another variable the file object in outfile is preserved.
Try this:
def newfield(infile,outfile):
items = ["%s\t%s" %(item.strip(),2) for item in infile]
outfile.write("\n".join(items))
outfile.close()
return outfile

Related

How to copy text from a file to a list in Python?

I have a couple of files inside a folder that I am trying to pull out text from, reason being that I eventually want to add this text into a newly created separate file. My tactic is to initialize a list and populate it with the text from each file, one by one. I have called this list myLines.
myLines = []
for line in f:
myLines.append(line)
for element in myLines:
f.write(myLines)
I get an error, and I know that it has something to do with .write() not accepting myLines because its a list rather than an argument. How would I go about turning the content of mylines into an acceptable argument for the write() method?
Thanks
IDK what's your intention of using myLines as the variable name. Given what you described it should be a list of texts, not a list of lines.
my_texts = []
# populate my_texts
for filename in input_files:
with open(filename) as f:
my_texts.append(f.read())
# write new file
with open('new_file_path.txt', 'w') as f:
f.write('\n'.join(my_texts))
assuming you want a new line separating texts from each file.
A more straightforward method would be to 1) open the output file in append mode (open('out_file_path', 'a')), and 2) read each input file in a loop, writing the content to the output file.
Try this -
myLines = []
for line in f:
myLines.append(line)
for element in myLines:
f.write(str(myLines))
Just convert myLines to string. You can use classes also if you want to preserve the type- list, but, that will be a bit lengthy.

Add a new list in a new line on a .txt file in python

I'm trying to add a list to an existing .txt file in Python three. Currently I have the following code:
def function(list, new_add):
with open("file.txt", new_add) as file:
for item in list:
file.write("{}\t".format(item))
add_grade(list, "w")
I have created a list:
list = [string1, integer1a, integer1b]
It works fine creating a new txt file. But if I replace "w" with "a" I do not get the purposed output. My question is now, how do I add new components of a list to the file in a new line? My current output look like this if I try to add new variables:
string1 integer1a integer1b string2 integer2a integer2a
I would like instead the following displayed:
string1 integer1a integer1b
string2 integer2a integer2a
...
How could I add a new line after the each list is inserted?
You can do this quite easily with the Python 3 print() function, just specify the separator and file with the sep and file parameters, and print() will take care of the details for you:
def function(iterable, filename, new_add):
with open(filename, new_add) as file:
print(*iterable, sep='\t', file=file)
Note that I renamed the list parameter to iterable because using list shadows the built-in list class, and the function should work with any iterable.
This code will also work in Python 2 if you add the following to the top of your file:
from __future__ import print_function
this should work , you should call line break after writing your list in the file
def add_grade(list, new_add):
with open("file.txt", new_add) as file:
for item in list:
file.write("{}\t".format(item))
file.write("\n")
add_grade(list, "w")

Printing as a dictionary in python

I have a problem in python. I want to create a function to print a file from user to a new file (example.txt).
The old file is like this:
{'a':1,'b':2...)
and I want the new file like:
a 1,b 2(the next line)
But the function which I made can run but it doesn't show anything in the new file. Can someone help me please.
def printing(file):
infile=open(file,'r')
outfile=open('example.txt','w')
dict={}
file=dict.values()
for key,values in file:
print key
print values
outfile.write(str(dict))
infile.close()
outfile.close()
This creates a new empty dictionary:
dict={}
dict is not a good name for a variable as it shadows the built-in type dict and could be confusing.
This makes the name file point at the values in the dictionary:
file=dict.values()
file will be empty because dict was empty.
This iterates over pairs of values in file.
for key,values in file:
As file is empty nothing will happen. However if file weren't empty, the values in it would have to be pairs of values to unpack them into key, values.
This converts dict to a string and writes it to the outfile:
outfile.write(str(dict))
Calling write with a non-str object will call str on it anway, so you could just say:
outfile.write(dict)
You don't actually do anything with infile.
You can use re module (regular expression) to achieve what you need. Solution could be like that. Of course you can customize to fit your need. Hope this helps.
import re
def printing(file):
outfile=open('example.txt','a')
with open(file,'r') as f:
for line in f:
new_string = re.sub('[^a-zA-Z0-9\n\.]', ' ', line)
outfile.write(new_string)
printing('output.txt')

Write a function that returns a data.txt in reverse [duplicate]

This question already has answers here:
How to read a file in reverse order?
(22 answers)
Closed 7 years ago.
I'm pretty new to Python programming and I have gotten stuck on how to return the data in a function in reverse.
For example, if data.txt contains:
Chaos reigns within.
Reflect, repent, and reboot
Order will return.
A call to write_reversed('data.txt') will print:
Order will return.
Reflect, repent, and reboot
Chaos reigns within.
The code I have currently written is
def write_reversed(filename):
"""returns with words in reverse order in the file"""
with open(filename, 'r') as write_reversed:
for line in write_reversed:
return filename[::-1]
I have pasted my code into a Pylint checker and it says "unused variable 'line'"
You are getting the unused variable error because (obviously) you aren't using the variable after declaration. Perhaps you meant:
for line in write_reversed:
return line[::-1]
However, you can do the following
def write_reversed(filename):
"""returns with words in reverse order in the file"""
content = []
with open(filename, 'r') as write_reversed:
for line in write_reversed:
content.append(line)
return list(reversed(content))
First, it says "unused variable line" because you never use line. You should be using it instead of filename - as it is, you're opening a file, then for each line in the file you return the filename backwards (which only happens once, because return will end the function).
Instead, build up a list, then return the reversed list.
def write_reversed(filename):
"""returns with words in reverse order in the file"""
reversed = []
with open(filename, 'r') as write_reversed:
for line in write_reversed:
reversed.append(line)
return reversed[::-1]
You’re reversing the filename instead of the lines of the file. There’s a reversed function available that returns an iterator over whatever you passed it in reverse. File objects are iterables (that’s why you can loop over their lines using for), so you can just pass yours directly to reversed:
def reversed_lines(filename):
"""returns with words in reverse order in the file"""
with open(filename, 'r') as f:
return list(reversed(f))
If the function should print the lines instead of returning them, just use your for with reversed(f) instead of f.
You can open the file.
readlines will return the lines in the file.
for l in F.readlines()[::-1]:
print l.strip()
will do the job
If you want to return the content, you just have to write this :
return "\n".join([l.strip() for l in F.readlines()[::-1]])
I have no idea what your question is, but this is a two-liner:
with open(filename, 'r') as f:
print(*reversed(f.readlines()), sep='')
You can also simply return the reversed lines as an iterator or a list:
with open(filename, 'r') as f:
return reversed(f.readlines()) # optional: wrap expr. in list()
Then printing your desired output is as simple as:
reversed_lines = write_reversed(filename)
print(*reversed_lines, sep='')
Note: write_reversed is a bad function name for a function that doesn't actually write anything to a buffer.

Python doesn't write all entries from list

I'm exploring python and tried to sort all files from a directory by last modified and then write the list into a txt file.
import time
import os
i=1
a="path"
def getfiles(dirpat):
b = [s for s in os.listdir(dirpat)
if os.path.isfile(os.path.join(dirpat, s))]
b.sort(key=lambda s: os.path.getmtime(os.path.join(dirpat, s)))
return b
lyst=[]
testfile='c://test.txt'
lyst=getfiles(a)
for x in range (0,len(lyst)):
print lyst[x]
fileHandle = open (testfile, 'w' )
fileHandle.write ("\n".join(str(lyst[x])))
fileHandle.close()
It printed perfectly and sorted by date also
example1.pdf
example3.docx
example4.docx
exmaple2.docx
example 5.doc
But when I opened the file, it just had the last entry and displayed it like this
e
x
a
... and so on
Just can't figure out where the problem lies. If I remove "\n".join it just prints me the last entry.
Thanks in advance,
Nils
Correct the join(), e.g:
'\n'.join(str(path) for path in list)
And please rename the "list" variable, because list is a built-in data type in Python.
import os, os.path
a="path"
def getfiles(dirpat):
b = [s for s in os.listdir(dirpat)
if os.path.isfile(os.path.join(dirpat, s))]
b.sort(key=lambda s: os.path.getmtime(os.path.join(dirpat, s)))
return b
outfile='c://test.txt'
with open(outfile, 'w') as fileHandle:
lines = getfiles(a)
for line in lines:
print line
fileHandle.write(line)
Avoid using meaningless one character variable names. I also did not touch your getfiles() function. I did, however, rename file and list as those are both the names of built in functions, which you're hiding when you use those names.
You also only need to open the file once, not once per line. You were truncating the file on every write. Using with makes sure the file handle gets closed even if you have an error.
Edit: If you don't need to print out each line before writing it, you can just have one line inside the with block: fileHandle.writelines(getfiles(a)).
You are opening and overwriting the file contents in each iteration of the loop.
Pass 'a' to the open(path) call to append to the file, or simply open it once outside the loop and close it outside the loop.
Because you convert each entry in the list to str the join operates on each
str because they also count as iterables and therefore a \n is put between
each character, not every item in the list. Changing the line to fileHandle.write ('\n'.join(str(path) for path in list))) will fix this just like BasicWolf wrote.
Do this when writing the file:
fileHandle = open (file, 'w' )
for listItem in list:
print listItem
fileHandle.write (str(listItem) + "\n")
fileHandle.close()

Categories