#!/usr/bin/python3.4
import urllib.request
import os
import re
os.chdir('/home/whatever/')
a = open('Shopstxt.csv','r')
b = a.readlines()
a.close()
c = len(b)
d = list(zip(*(e.split(';') for e in b)))
shopname = []
shopaddress = []
shopcity = []
shopphone = []
shopwebsite = []
f = d[0]
g = d[1]
h = d[2]
i = d[3]
j = d[4]
e = -1
for n in range(0, 5):
e = e + 1
sn = f[n]
sn.title()
print(sn)
shopname.append(sn)
sa = g[n]
sa.title()
shopaddress.append(sa)
sc = h[n]
sc.title()
shopcity.append(sc)
Shopstxt.csv是大写字母,我想将它们转换为标题。我认为这样做会但是它不会......它仍然会让它们全部成为大写。我做错了什么?
我还想保存文件。只是想要快速检查一些事情......时间紧迫。
当我将文件重新组合在一起时,在将其写回驱动器之前,我必须在每行的末尾添加'\ n',或者当我将每行写入时自动包含'\ n'文件?
答案 0 :(得分:0)
字符串是不可变的,因此您需要指定title()
:
sa = sa.title()
sc = sc.title()
另外,如果你这样做:
with open("bla.txt", "wt") as outfile:
outfile.write("stuff")
outfile.write("more stuff")
然后这将不自动添加行结尾。
添加行结尾的快速方法是:
textblobb = "\n".join(list_of_text_lines)
with open("bla.txt", "wt") as outfile:
outfile.write(textblobb)
只要textblobb
效率不高且适合内存,就可以很好地完成这项工作。
答案 1 :(得分:0)
在定义变量时使用.title()
方法,就像我在下面的代码中所做的那样。正如其他人所提到的,字符串是不可变的,所以请保存一步并在一行中创建所需的字符串。
for n in range(0, 5):
e = e + 1
sn = f[n].title() ### Grab and modify the list index before assigning to your variable
print(sn)
shopname.append(sn)
sa = g[n].title() ###
shopaddress.append(sa)
sc = h[n].title() ###
shopcity.append(sc)