Write strings to file in append mode¶
Let us see how we can write multiple strings from a list to file in append mode.
- We cannot write the list of strings into file properly all at once.
In [1]:
departments = [
'2,Fitness',
'3,Footwear',
'4,Apparel',
'5,Golf',
'6,Outdoors',
'7,Fan Shop'
]
In [2]:
file = open('data/departments.txt', 'w')
In [3]:
file.write(departments) # Fails
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [3], in <cell line: 1>() ----> 1 file.write(departments) TypeError: write() argument must be str, not list
In [4]:
file.close()
Here are the steps involved in writing list of strings in the form of CSV to a file.
- Make sure that data in the list contains delimited strings.
- Open the file in append mode.
- Iterate through the list and write one element at a time into the file.
- Close the file.
Make sure to validate whether data is written properly or not in the file.
In [5]:
departments = [
'2,Fitness',
'3,Footwear',
'4,Apparel',
'5,Golf',
'6,Outdoors',
'7,Fan Shop'
]
In [6]:
file = open('data/departments.txt', 'a')
In [7]:
for department in departments:
file.write(department)
In [8]:
file.close()
In [9]:
!ls -ltr data/departments.txt
-rw-rw-r-- 1 itversity itversity 54 Mar 25 06:06 data/departments.txt
In [10]:
!cat data/departments.txt # No new line characters
2,Fitness3,Footwear4,Apparel5,Golf6,Outdoors7,Fan Shop
In [11]:
!rm data/departments.txt
In [12]:
departments = [
'2,Fitness',
'3,Footwear',
'4,Apparel',
'5,Golf',
'6,Outdoors',
'7,Fan Shop'
]
In [13]:
file = open('data/departments.txt', 'a')
In [14]:
for department in departments:
file.write(f'{department}\n')
In [15]:
file.close()
In [16]:
!ls -ltr data/departments.txt
-rw-r--r-- 1 itversity itversity 60 Mar 25 06:06 data/departments.txt
In [17]:
!cat data/departments.txt # With new line characters
2,Fitness 3,Footwear 4,Apparel 5,Golf 6,Outdoors 7,Fan Shop
In [18]:
!wc -l data/departments.txt
6 data/departments.txt
- You can also build one big string and write into the file in one shot. However you need to ensure that the line delimiter is placed between the elements.
In [19]:
!rm data/departments.txt
In [20]:
departments = [
'2,Fitness',
'3,Footwear',
'4,Apparel',
'5,Golf',
'6,Outdoors',
'7,Fan Shop'
]
In [21]:
data = '\n'.join(departments)
In [22]:
type(data)
Out[22]:
str
In [23]:
data
Out[23]:
'2,Fitness\n3,Footwear\n4,Apparel\n5,Golf\n6,Outdoors\n7,Fan Shop'
In [24]:
file = open('data/departments.txt', 'a')
In [25]:
file.write(data)
Out[25]:
59
In [26]:
file.close()
In [27]:
!ls -ltr data/departments.txt
-rw-r--r-- 1 itversity itversity 59 Mar 25 06:06 data/departments.txt
In [28]:
!cat data/departments.txt # With new line characters
2,Fitness 3,Footwear 4,Apparel 5,Golf 6,Outdoors 7,Fan Shop
In [29]:
!wc -l data/departments.txt
5 data/departments.txt