2016-09-29 74 views
0
#!/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

字符串是不可改变的,所以你需要ASIGN的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不是低效大,能够装入内存,应该很好做的伎俩。

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)